blob: 2d2fd53447eecd743c4bcdce505cf9c804018e34 [file] [log] [blame]
Nate Begeman4ebd8052005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman1d4d4142005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Begeman1d4d4142005-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 Michelfdc40a02009-02-17 22:15:04 +000012//
Dan Gohman41287002009-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 Begeman1d4d4142005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman1d4d4142005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/LLVMContext.h"
Jim Laskeyd1aed7a2006-09-21 16:28:59 +000029#include "llvm/Support/CommandLine.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000030#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc76d4412007-05-16 06:37:59 +000032#include "llvm/Support/MathExtras.h"
Chris Lattnerbbbfa992009-08-23 06:35:02 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Quentin Colombet83f743a2013-10-11 18:29:42 +000037#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel253acef2013-08-29 03:29:55 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnera500fc62005-09-09 23:53:39 +000039#include <algorithm>
Nate Begeman1d4d4142005-09-01 00:19:25 +000040using namespace llvm;
41
Stephen Hinesdce4a402014-05-29 02:49:00 -070042#define DEBUG_TYPE "dagcombine"
43
Chris Lattnercd3245a2006-12-19 22:41:21 +000044STATISTIC(NodesCombined , "Number of dag nodes combined");
45STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Cheng8b944d32009-05-28 00:35:15 +000047STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Cheng31959b12011-02-02 01:06:55 +000048STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombet83f743a2013-10-11 18:29:42 +000049STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattnercd3245a2006-12-19 22:41:21 +000050
Nate Begeman1d4d4142005-09-01 00:19:25 +000051namespace {
Jim Laskey71382342006-10-07 23:37:56 +000052 static cl::opt<bool>
Owen Anderson0dcc8142010-09-19 21:01:26 +000053 CombinerAA("combiner-alias-analysis", cl::Hidden,
Stephen Hines36b56882014-04-23 16:57:46 -070054 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskey3ad175b2006-10-12 15:22:24 +000055
Jim Laskey07a27092006-10-18 19:08:31 +000056 static cl::opt<bool>
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Stephen Hines36b56882014-04-23 16:57:46 -070058 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
Stephen Hines36b56882014-04-23 16:57:46 -070060 static cl::opt<bool>
Stephen Hinesdce4a402014-05-29 02:49:00 -070061 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Stephen Hines36b56882014-04-23 16:57:46 -070062 cl::desc("Enable DAG combiner's use of TBAA"));
63
64#ifndef NDEBUG
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
68 " function"));
69#endif
Jim Laskey07a27092006-10-18 19:08:31 +000070
Quentin Colombet83f743a2013-10-11 18:29:42 +000071 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
73 static cl::opt<bool>
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
76 "slicing"),
77 cl::init(false));
78
Jim Laskeybc588b82006-10-05 15:07:25 +000079//------------------------------ DAGCombiner ---------------------------------//
80
Nick Lewycky6726b6d2009-10-25 06:33:48 +000081 class DAGCombiner {
Nate Begeman1d4d4142005-09-01 00:19:25 +000082 SelectionDAG &DAG;
Dan Gohman79ce2762009-01-15 19:20:50 +000083 const TargetLowering &TLI;
Duncan Sands25cf2272008-11-24 14:53:14 +000084 CombineLevel Level;
Bill Wendling98a366d2009-04-29 23:29:43 +000085 CodeGenOpt::Level OptLevel;
Duncan Sands25cf2272008-11-24 14:53:14 +000086 bool LegalOperations;
87 bool LegalTypes;
Quentin Colombet83f743a2013-10-11 18:29:42 +000088 bool ForCodeSize;
Nate Begeman1d4d4142005-09-01 00:19:25 +000089
90 // Worklist of all of the nodes that need to be simplified.
James Molloy6660c052012-02-16 09:17:04 +000091 //
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
95 // linear time.
96 //
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
99 //
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
102 //
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramerd5f76902012-03-10 00:23:58 +0000108 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman1d4d4142005-09-01 00:19:25 +0000109
Jim Laskeyc7c3f112006-10-16 20:52:31 +0000110 // AA - Used for DAG load/store alias analysis.
111 AliasAnalysis &AA;
112
Nate Begeman1d4d4142005-09-01 00:19:25 +0000113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
115 /// now.
116 ///
117 void AddUsersToWorkList(SDNode *N) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700118 for (SDNode *Node : N->uses())
119 AddToWorkList(Node);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000120 }
121
Dan Gohman389079b2007-10-08 17:57:15 +0000122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
Dan Gohman475871a2008-07-27 21:46:04 +0000124 SDValue visit(SDNode *N);
Dan Gohman389079b2007-10-08 17:57:15 +0000125
Chris Lattner24664722006-03-01 04:53:38 +0000126 public:
James Molloy6afa3f72012-02-16 09:48:07 +0000127 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy6660c052012-02-16 09:17:04 +0000128 /// back (next to be processed.)
Chris Lattner5750df92006-03-01 04:03:14 +0000129 void AddToWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
Chris Lattner5750df92006-03-01 04:03:14 +0000132 }
Jim Laskey6ff23e52006-10-04 16:53:27 +0000133
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000134 /// removeFromWorkList - remove all instances of N from the worklist.
135 ///
136 void removeFromWorkList(SDNode *N) {
James Molloy6660c052012-02-16 09:17:04 +0000137 WorkListContents.erase(N);
Chris Lattner01a22022005-10-10 22:04:48 +0000138 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000139
Dan Gohman475871a2008-07-27 21:46:04 +0000140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000141 bool AddTo = true);
Scott Michelfdc40a02009-02-17 22:15:04 +0000142
Dan Gohman475871a2008-07-27 21:46:04 +0000143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskey274062c2006-10-13 23:32:28 +0000144 return CombineTo(N, &Res, 1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000145 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000146
Dan Gohman475871a2008-07-27 21:46:04 +0000147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Cheng0b0cd912009-03-28 05:57:29 +0000148 bool AddTo = true) {
Dan Gohman475871a2008-07-27 21:46:04 +0000149 SDValue To[] = { Res0, Res1 };
Jim Laskey274062c2006-10-13 23:32:28 +0000150 return CombineTo(N, To, 2, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000151 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000152
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelfdc40a02009-02-17 22:15:04 +0000154
155 private:
156
Chris Lattner012f2412006-02-17 21:58:01 +0000157 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattnerb2742f42006-03-01 19:55:35 +0000158 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner012f2412006-02-17 21:58:01 +0000159 /// propagation. If so, return true.
Dan Gohman475871a2008-07-27 21:46:04 +0000160 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman87862e72009-12-11 21:31:27 +0000161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohman7b8d4a92008-02-27 00:25:32 +0000163 return SimplifyDemandedBits(Op, Demanded);
164 }
165
Dan Gohman475871a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner87514ca2005-10-10 22:31:19 +0000167
Chris Lattner448f2192006-11-11 00:39:41 +0000168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700170 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombet83f743a2013-10-11 18:29:42 +0000171 bool SliceUpLoad(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000172
Evan Cheng95c57ea2010-04-24 04:43:44 +0000173 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
174 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
175 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
176 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000177 SDValue PromoteIntBinOp(SDValue Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000178 SDValue PromoteIntShiftOp(SDValue Op);
Evan Cheng4c26e932010-04-19 19:29:22 +0000179 SDValue PromoteExtend(SDValue Op);
180 bool PromoteLoad(SDValue Op);
Scott Michelfdc40a02009-02-17 22:15:04 +0000181
Craig Topper6c64fba2013-07-13 07:43:40 +0000182 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000183 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +0000184 ISD::NodeType ExtType);
185
Dan Gohman389079b2007-10-08 17:57:15 +0000186 /// combine - call the node-specific routine that knows how to fold each
187 /// particular type of node. If that doesn't do anything, try the
188 /// target-specific DAG combines.
Dan Gohman475871a2008-07-27 21:46:04 +0000189 SDValue combine(SDNode *N);
Nate Begeman1d4d4142005-09-01 00:19:25 +0000190
191 // Visitation implementation - Implement dag node combining for different
192 // node types. The semantics are as follows:
193 // Return Value:
Evan Cheng17a568b2008-08-29 22:21:44 +0000194 // SDValue.getNode() == 0 - No change was made
195 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
196 // otherwise - N should be replaced by the returned Operand.
Nate Begeman1d4d4142005-09-01 00:19:25 +0000197 //
Dan Gohman475871a2008-07-27 21:46:04 +0000198 SDValue visitTokenFactor(SDNode *N);
199 SDValue visitMERGE_VALUES(SDNode *N);
200 SDValue visitADD(SDNode *N);
201 SDValue visitSUB(SDNode *N);
202 SDValue visitADDC(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000203 SDValue visitSUBC(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000204 SDValue visitADDE(SDNode *N);
Craig Toppercc274522012-01-07 09:06:39 +0000205 SDValue visitSUBE(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000206 SDValue visitMUL(SDNode *N);
207 SDValue visitSDIV(SDNode *N);
208 SDValue visitUDIV(SDNode *N);
209 SDValue visitSREM(SDNode *N);
210 SDValue visitUREM(SDNode *N);
211 SDValue visitMULHU(SDNode *N);
212 SDValue visitMULHS(SDNode *N);
213 SDValue visitSMUL_LOHI(SDNode *N);
214 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +0000215 SDValue visitSMULO(SDNode *N);
216 SDValue visitUMULO(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000217 SDValue visitSDIVREM(SDNode *N);
218 SDValue visitUDIVREM(SDNode *N);
219 SDValue visitAND(SDNode *N);
220 SDValue visitOR(SDNode *N);
221 SDValue visitXOR(SDNode *N);
222 SDValue SimplifyVBinOp(SDNode *N);
Craig Topperdd201ff2012-09-11 01:45:21 +0000223 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000224 SDValue visitSHL(SDNode *N);
225 SDValue visitSRA(SDNode *N);
226 SDValue visitSRL(SDNode *N);
Stephen Hines36b56882014-04-23 16:57:46 -0700227 SDValue visitRotate(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000228 SDValue visitCTLZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000229 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000230 SDValue visitCTTZ(SDNode *N);
Chandler Carruth63974b22011-12-13 01:56:10 +0000231 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000232 SDValue visitCTPOP(SDNode *N);
233 SDValue visitSELECT(SDNode *N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +0000234 SDValue visitVSELECT(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000235 SDValue visitSELECT_CC(SDNode *N);
236 SDValue visitSETCC(SDNode *N);
237 SDValue visitSIGN_EXTEND(SDNode *N);
238 SDValue visitZERO_EXTEND(SDNode *N);
239 SDValue visitANY_EXTEND(SDNode *N);
240 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
241 SDValue visitTRUNCATE(SDNode *N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000242 SDValue visitBITCAST(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000243 SDValue visitBUILD_PAIR(SDNode *N);
244 SDValue visitFADD(SDNode *N);
245 SDValue visitFSUB(SDNode *N);
246 SDValue visitFMUL(SDNode *N);
Owen Anderson062c0a52012-05-02 22:17:40 +0000247 SDValue visitFMA(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000248 SDValue visitFDIV(SDNode *N);
249 SDValue visitFREM(SDNode *N);
250 SDValue visitFCOPYSIGN(SDNode *N);
251 SDValue visitSINT_TO_FP(SDNode *N);
252 SDValue visitUINT_TO_FP(SDNode *N);
253 SDValue visitFP_TO_SINT(SDNode *N);
254 SDValue visitFP_TO_UINT(SDNode *N);
255 SDValue visitFP_ROUND(SDNode *N);
256 SDValue visitFP_ROUND_INREG(SDNode *N);
257 SDValue visitFP_EXTEND(SDNode *N);
258 SDValue visitFNEG(SDNode *N);
259 SDValue visitFABS(SDNode *N);
Owen Anderson7c626d32012-08-13 23:32:49 +0000260 SDValue visitFCEIL(SDNode *N);
261 SDValue visitFTRUNC(SDNode *N);
262 SDValue visitFFLOOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000263 SDValue visitBRCOND(SDNode *N);
264 SDValue visitBR_CC(SDNode *N);
265 SDValue visitLOAD(SDNode *N);
266 SDValue visitSTORE(SDNode *N);
267 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
268 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
269 SDValue visitBUILD_VECTOR(SDNode *N);
270 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +0000271 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman475871a2008-07-27 21:46:04 +0000272 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Stephen Hines36b56882014-04-23 16:57:46 -0700273 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattner01a22022005-10-10 22:04:48 +0000274
Dan Gohman475871a2008-07-27 21:46:04 +0000275 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000276 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelfdc40a02009-02-17 22:15:04 +0000277
Stephen Hines36b56882014-04-23 16:57:46 -0700278 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattnere70da202007-12-06 07:33:36 +0000279
Dan Gohman475871a2008-07-27 21:46:04 +0000280 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
281 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000282 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
283 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelfdc40a02009-02-17 22:15:04 +0000284 SDValue N3, ISD::CondCode CC,
Bill Wendling836ca7d2009-01-30 23:59:18 +0000285 bool NotExtCompare = false);
Owen Andersone50ed302009-08-10 22:56:29 +0000286 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000287 SDLoc DL, bool foldBooleans = true);
Stephen Hines36b56882014-04-23 16:57:46 -0700288
289 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
290 SDValue &CC) const;
291 bool isOneUseSetCC(SDValue N) const;
292
Scott Michelfdc40a02009-02-17 22:15:04 +0000293 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner5eee4272008-01-26 01:09:19 +0000294 unsigned HiOp);
Owen Andersone50ed302009-08-10 22:56:29 +0000295 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000296 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman475871a2008-07-27 21:46:04 +0000297 SDValue BuildSDIV(SDNode *N);
298 SDValue BuildUDIV(SDNode *N);
Evan Cheng9568e5c2011-06-21 06:01:08 +0000299 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300 bool DemandHighBits = true);
301 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Stephen Hines36b56882014-04-23 16:57:46 -0700302 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303 SDValue InnerPos, SDValue InnerNeg,
304 unsigned PosOpcode, unsigned NegOpcode,
305 SDLoc DL);
Andrew Trickac6d9be2013-05-25 02:42:55 +0000306 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman475871a2008-07-27 21:46:04 +0000307 SDValue ReduceLoadWidth(SDNode *N);
Evan Cheng8b944d32009-05-28 00:35:15 +0000308 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Cheng31959b12011-02-02 01:06:55 +0000309 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liaofac14ab2012-10-23 23:06:52 +0000310 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao1a5cc712012-10-24 04:14:18 +0000311 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000312
Dan Gohman475871a2008-07-27 21:46:04 +0000313 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelfdc40a02009-02-17 22:15:04 +0000314
Jim Laskey6ff23e52006-10-04 16:53:27 +0000315 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +0000317 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000318 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey6ff23e52006-10-04 16:53:27 +0000319
Jim Laskey096c22e2006-10-18 12:29:57 +0000320 /// isAlias - Return true if there is any possibility that the two addresses
321 /// overlap.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700322 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelfdc40a02009-02-17 22:15:04 +0000323
Jim Laskey279f0532006-09-25 16:29:54 +0000324 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey6ff23e52006-10-04 16:53:27 +0000325 /// looking for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +0000326 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands92abc622009-01-31 15:50:11 +0000327
Nadav Rotemc653de62012-10-03 16:11:15 +0000328 /// Merge consecutive store operations into a wide store.
329 /// This optimization uses wide integers or vectors when possible.
330 /// \return True if some memory operations were changed.
331 bool MergeConsecutiveStores(StoreSDNode *N);
332
Stephen Hines36b56882014-04-23 16:57:46 -0700333 /// \brief Try to transform a truncation where C is a constant:
334 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
335 ///
336 /// \p N needs to be a truncation and its first operand an AND. Other
337 /// requirements are checked by the function (e.g. that trunc is
338 /// single-use) and if missed an empty SDValue is returned.
339 SDValue distributeTruncateThroughAnd(SDNode *N);
340
Chris Lattner2392ae72010-04-15 04:48:01 +0000341 public:
Bill Wendling98a366d2009-04-29 23:29:43 +0000342 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombet83f743a2013-10-11 18:29:42 +0000343 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
344 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
345 AttributeSet FnAttrs =
346 DAG.getMachineFunction().getFunction()->getAttributes();
347 ForCodeSize =
348 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
349 Attribute::OptimizeForSize) ||
350 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
351 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000352
Nate Begeman1d4d4142005-09-01 00:19:25 +0000353 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sands25cf2272008-11-24 14:53:14 +0000354 void Run(CombineLevel AtLevel);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000355
Chris Lattner2392ae72010-04-15 04:48:01 +0000356 SelectionDAG &getDAG() const { return DAG; }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000357
Chris Lattner2392ae72010-04-15 04:48:01 +0000358 /// getShiftAmountTy - Returns a type large enough to hold any valid
359 /// shift amount - before type legalization these can be huge.
Owen Anderson95771af2011-02-25 21:41:48 +0000360 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +0000361 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
362 if (LHSTy.isVector())
363 return LHSTy;
Jack Carteradbd3ae2013-10-17 01:34:33 +0000364 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
365 : TLI.getPointerTy();
Chris Lattner2392ae72010-04-15 04:48:01 +0000366 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000367
Chris Lattner2392ae72010-04-15 04:48:01 +0000368 /// isTypeLegal - This method returns true if we are running before type
369 /// legalization or if the specified VT is legal.
370 bool isTypeLegal(const EVT &VT) {
371 if (!LegalTypes) return true;
372 return TLI.isTypeLegal(VT);
373 }
Matt Arsenault225ed702013-05-18 00:21:46 +0000374
375 /// getSetCCResultType - Convenience wrapper around
376 /// TargetLowering::getSetCCResultType
377 EVT getSetCCResultType(EVT VT) const {
378 return TLI.getSetCCResultType(*DAG.getContext(), VT);
379 }
Nate Begeman1d4d4142005-09-01 00:19:25 +0000380 };
381}
382
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000383
384namespace {
385/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
386/// nodes from the worklist.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000387class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000388 DAGCombiner &DC;
389public:
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000390 explicit WorkListRemover(DAGCombiner &dc)
391 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelfdc40a02009-02-17 22:15:04 +0000392
Stephen Hines36b56882014-04-23 16:57:46 -0700393 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000394 DC.removeFromWorkList(N);
395 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000396};
397}
398
Chris Lattner24664722006-03-01 04:53:38 +0000399//===----------------------------------------------------------------------===//
400// TargetLowering::DAGCombinerInfo implementation
401//===----------------------------------------------------------------------===//
402
403void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
404 ((DAGCombiner*)DC)->AddToWorkList(N);
405}
406
Cameron Zwariched3caf92011-04-02 02:40:26 +0000407void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
408 ((DAGCombiner*)DC)->removeFromWorkList(N);
409}
410
Dan Gohman475871a2008-07-27 21:46:04 +0000411SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000412CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
413 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000414}
415
Dan Gohman475871a2008-07-27 21:46:04 +0000416SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000417CombineTo(SDNode *N, SDValue Res, bool AddTo) {
418 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000419}
420
421
Dan Gohman475871a2008-07-27 21:46:04 +0000422SDValue TargetLowering::DAGCombinerInfo::
Evan Cheng0b0cd912009-03-28 05:57:29 +0000423CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
424 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattner24664722006-03-01 04:53:38 +0000425}
426
Dan Gohmane5af2d32009-01-29 01:59:02 +0000427void TargetLowering::DAGCombinerInfo::
428CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
429 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
430}
Chris Lattner24664722006-03-01 04:53:38 +0000431
Chris Lattner24664722006-03-01 04:53:38 +0000432//===----------------------------------------------------------------------===//
Chris Lattner29446522007-05-14 22:04:50 +0000433// Helper Functions
434//===----------------------------------------------------------------------===//
435
436/// isNegatibleForFree - Return 1 if we can compute the negated form of the
437/// specified expression for the same cost as the expression itself, or 2 if we
438/// can compute the negated form more cheaply than the expression itself.
Duncan Sands25cf2272008-11-24 14:53:14 +0000439static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000440 const TargetLowering &TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000441 const TargetOptions *Options,
Chris Lattner0254e702008-02-26 07:04:54 +0000442 unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000443 // fneg is removable even if it has multiple uses.
444 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelfdc40a02009-02-17 22:15:04 +0000445
Chris Lattner29446522007-05-14 22:04:50 +0000446 // Don't allow anything with multiple uses.
447 if (!Op.hasOneUse()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000448
Chris Lattner3adf9512007-05-25 02:19:06 +0000449 // Don't recurse exponentially.
450 if (Depth > 6) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000451
Chris Lattner29446522007-05-14 22:04:50 +0000452 switch (Op.getOpcode()) {
453 default: return false;
454 case ISD::ConstantFP:
Chris Lattner0254e702008-02-26 07:04:54 +0000455 // Don't invert constant FP values after legalize. The negated constant
456 // isn't necessarily legal.
Duncan Sands25cf2272008-11-24 14:53:14 +0000457 return LegalOperations ? 0 : 1;
Chris Lattner29446522007-05-14 22:04:50 +0000458 case ISD::FADD:
459 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000460 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000461
Owen Andersonafd3d562012-03-06 00:29:31 +0000462 // After operation legalization, it might not be legal to create new FSUBs.
463 if (LegalOperations &&
464 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
465 return 0;
466
Craig Topper956342b2012-09-09 22:58:45 +0000467 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Andersonafd3d562012-03-06 00:29:31 +0000468 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
469 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000470 return V;
Bill Wendlingd34470c2009-01-30 23:10:18 +0000471 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Andersonafd3d562012-03-06 00:29:31 +0000472 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000473 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000474 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000475 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000476 if (!Options->UnsafeFPMath) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000477
Bill Wendlingd34470c2009-01-30 23:10:18 +0000478 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattner29446522007-05-14 22:04:50 +0000479 return 1;
Scott Michelfdc40a02009-02-17 22:15:04 +0000480
Chris Lattner29446522007-05-14 22:04:50 +0000481 case ISD::FMUL:
482 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000483 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelfdc40a02009-02-17 22:15:04 +0000484
Bill Wendlingd34470c2009-01-30 23:10:18 +0000485 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Andersonafd3d562012-03-06 00:29:31 +0000486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487 Options, Depth + 1))
Chris Lattner29446522007-05-14 22:04:50 +0000488 return V;
Scott Michelfdc40a02009-02-17 22:15:04 +0000489
Owen Andersonafd3d562012-03-06 00:29:31 +0000490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000491 Depth + 1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000492
Chris Lattner29446522007-05-14 22:04:50 +0000493 case ISD::FP_EXTEND:
494 case ISD::FP_ROUND:
495 case ISD::FSIN:
Owen Andersonafd3d562012-03-06 00:29:31 +0000496 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000497 Depth + 1);
Chris Lattner29446522007-05-14 22:04:50 +0000498 }
499}
500
501/// GetNegatedExpression - If isNegatibleForFree returns true, this function
502/// returns the newly negated expression.
Dan Gohman475871a2008-07-27 21:46:04 +0000503static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000504 bool LegalOperations, unsigned Depth = 0) {
Chris Lattner29446522007-05-14 22:04:50 +0000505 // fneg is removable even if it has multiple uses.
506 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000507
Chris Lattner29446522007-05-14 22:04:50 +0000508 // Don't allow anything with multiple uses.
509 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000510
Chris Lattner3adf9512007-05-25 02:19:06 +0000511 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattner29446522007-05-14 22:04:50 +0000512 switch (Op.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000513 default: llvm_unreachable("Unknown code");
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000514 case ISD::ConstantFP: {
515 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
516 V.changeSign();
517 return DAG.getConstantFP(V, Op.getValueType());
518 }
Chris Lattner29446522007-05-14 22:04:50 +0000519 case ISD::FADD:
520 // FIXME: determine better conditions for this xform.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000521 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelfdc40a02009-02-17 22:15:04 +0000522
Bill Wendlingd34470c2009-01-30 23:10:18 +0000523 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000524 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000525 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000526 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000527 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000528 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000529 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000530 Op.getOperand(1));
Bill Wendlingd34470c2009-01-30 23:10:18 +0000531 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000532 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000533 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000534 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000535 Op.getOperand(0));
536 case ISD::FSUB:
Scott Michelfdc40a02009-02-17 22:15:04 +0000537 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000538 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman23ff1822007-07-02 15:48:56 +0000539
Bill Wendlingd34470c2009-01-30 23:10:18 +0000540 // fold (fneg (fsub 0, B)) -> B
Dan Gohman23ff1822007-07-02 15:48:56 +0000541 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesenc4dd3c32007-08-31 23:34:27 +0000542 if (N0CFP->getValueAPF().isZero())
Dan Gohman23ff1822007-07-02 15:48:56 +0000543 return Op.getOperand(1);
Scott Michelfdc40a02009-02-17 22:15:04 +0000544
Bill Wendlingd34470c2009-01-30 23:10:18 +0000545 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickac6d9be2013-05-25 02:42:55 +0000546 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendling35247c32009-01-30 00:45:56 +0000547 Op.getOperand(1), Op.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +0000548
Chris Lattner29446522007-05-14 22:04:50 +0000549 case ISD::FMUL:
550 case ISD::FDIV:
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000551 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelfdc40a02009-02-17 22:15:04 +0000552
Bill Wendlingd34470c2009-01-30 23:10:18 +0000553 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000554 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Andersonafd3d562012-03-06 00:29:31 +0000555 DAG.getTargetLoweringInfo(),
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000556 &DAG.getTarget().Options, Depth+1))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000557 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000558 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000559 LegalOperations, Depth+1),
Chris Lattner29446522007-05-14 22:04:50 +0000560 Op.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000561
Bill Wendlingd34470c2009-01-30 23:10:18 +0000562 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickac6d9be2013-05-25 02:42:55 +0000563 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattner29446522007-05-14 22:04:50 +0000564 Op.getOperand(0),
Chris Lattner0254e702008-02-26 07:04:54 +0000565 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000566 LegalOperations, Depth+1));
Scott Michelfdc40a02009-02-17 22:15:04 +0000567
Chris Lattner29446522007-05-14 22:04:50 +0000568 case ISD::FP_EXTEND:
Chris Lattner29446522007-05-14 22:04:50 +0000569 case ISD::FSIN:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000570 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000571 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000572 LegalOperations, Depth+1));
Chris Lattner0bd48932008-01-17 07:00:52 +0000573 case ISD::FP_ROUND:
Andrew Trickac6d9be2013-05-25 02:42:55 +0000574 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000575 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sands25cf2272008-11-24 14:53:14 +0000576 LegalOperations, Depth+1),
Chris Lattner0bd48932008-01-17 07:00:52 +0000577 Op.getOperand(1));
Chris Lattner29446522007-05-14 22:04:50 +0000578 }
579}
Chris Lattner24664722006-03-01 04:53:38 +0000580
Nate Begeman4ebd8052005-09-01 23:24:04 +0000581// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Stephen Hines36b56882014-04-23 16:57:46 -0700582// that selects between the target values used for true and false, making it
583// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
584// the appropriate nodes based on the type of node we are checking. This
585// simplifies life a bit for the callers.
586bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
587 SDValue &CC) const {
Nate Begeman646d7e22005-09-02 21:18:40 +0000588 if (N.getOpcode() == ISD::SETCC) {
589 LHS = N.getOperand(0);
590 RHS = N.getOperand(1);
591 CC = N.getOperand(2);
Nate Begeman4ebd8052005-09-01 23:24:04 +0000592 return true;
Nate Begeman646d7e22005-09-02 21:18:40 +0000593 }
Stephen Hines36b56882014-04-23 16:57:46 -0700594
595 if (N.getOpcode() != ISD::SELECT_CC ||
596 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
597 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
598 return false;
599
600 LHS = N.getOperand(0);
601 RHS = N.getOperand(1);
602 CC = N.getOperand(4);
603 return true;
Nate Begeman1d4d4142005-09-01 00:19:25 +0000604}
605
Nate Begeman99801192005-09-07 23:25:52 +0000606// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
607// one use. If this is true, it allows the users to invert the operation for
608// free when it is profitable to do so.
Stephen Hines36b56882014-04-23 16:57:46 -0700609bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman475871a2008-07-27 21:46:04 +0000610 SDValue N0, N1, N2;
Gabor Greifba36cb52008-08-28 21:40:38 +0000611 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman4ebd8052005-09-01 23:24:04 +0000612 return true;
613 return false;
614}
615
Stephen Hines36b56882014-04-23 16:57:46 -0700616/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
617/// elements are all the same constant or undefined.
618static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
619 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
620 if (!C)
621 return false;
622
623 APInt SplatUndef;
624 unsigned SplatBitSize;
625 bool HasAnyUndefs;
626 EVT EltVT = N->getValueType(0).getVectorElementType();
627 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
628 HasAnyUndefs) &&
629 EltVT.getSizeInBits() >= SplatBitSize);
630}
631
632// \brief Returns the SDNode if it is a constant BuildVector or constant.
633static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
634 if (isa<ConstantSDNode>(N))
635 return N.getNode();
636 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
637 if(BV && BV->isConstant())
638 return BV;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700639 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700640}
641
642// \brief Returns the SDNode if it is a constant splat BuildVector or constant
643// int.
644static ConstantSDNode *isConstOrConstSplat(SDValue N) {
645 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
646 return CN;
647
Stephen Hinesdce4a402014-05-29 02:49:00 -0700648 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
649 ConstantSDNode *CN = BV->getConstantSplatValue();
650
651 // BuildVectors can truncate their operands. Ignore that case here.
652 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
653 return CN;
654 }
Stephen Hines36b56882014-04-23 16:57:46 -0700655
656 return nullptr;
657}
658
Andrew Trickac6d9be2013-05-25 02:42:55 +0000659SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendling35247c32009-01-30 00:45:56 +0000660 SDValue N0, SDValue N1) {
Owen Andersone50ed302009-08-10 22:56:29 +0000661 EVT VT = N0.getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -0700662 if (N0.getOpcode() == Opc) {
663 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
664 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
665 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
666 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
667 if (!OpNode.getNode())
668 return SDValue();
669 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
670 }
671 if (N0.hasOneUse()) {
672 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
673 // use
674 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
675 if (!OpNode.getNode())
676 return SDValue();
677 AddToWorkList(OpNode.getNode());
678 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
679 }
Nate Begemancd4d58c2006-02-03 06:46:56 +0000680 }
681 }
Bill Wendling35247c32009-01-30 00:45:56 +0000682
Stephen Hines36b56882014-04-23 16:57:46 -0700683 if (N1.getOpcode() == Opc) {
684 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
685 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
686 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
687 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
688 if (!OpNode.getNode())
689 return SDValue();
690 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
691 }
692 if (N1.hasOneUse()) {
693 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
694 // use
695 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
696 if (!OpNode.getNode())
697 return SDValue();
698 AddToWorkList(OpNode.getNode());
699 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
700 }
Nate Begemancd4d58c2006-02-03 06:46:56 +0000701 }
702 }
Bill Wendling35247c32009-01-30 00:45:56 +0000703
Dan Gohman475871a2008-07-27 21:46:04 +0000704 return SDValue();
Nate Begemancd4d58c2006-02-03 06:46:56 +0000705}
706
Dan Gohman475871a2008-07-27 21:46:04 +0000707SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
708 bool AddTo) {
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000709 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
710 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +0000711 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000712 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000713 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000714 To[0].getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000715 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000716 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen9f0d4e62009-12-03 05:15:35 +0000717 assert((!To[i].getNode() ||
718 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman764fd0c2009-01-21 15:17:51 +0000719 "Cannot combine value to value of different type!"));
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000720 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000721 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000722 if (AddTo) {
723 // Push the new nodes and any users onto the worklist
724 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattnerd1980a52009-03-12 06:52:53 +0000725 if (To[i].getNode()) {
726 AddToWorkList(To[i].getNode());
727 AddUsersToWorkList(To[i].getNode());
728 }
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000729 }
730 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000731
Dan Gohmandbe664a2009-01-19 21:44:21 +0000732 // Finally, if the node is now dead, remove it from the graph. The node
733 // may not be dead if the replacement process recursively simplified to
734 // something else needing this node.
735 if (N->use_empty()) {
736 // Nodes can be reintroduced into the worklist. Make sure we do not
737 // process a node that has been replaced.
738 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +0000739
Dan Gohmandbe664a2009-01-19 21:44:21 +0000740 // Finally, since the node is now dead, remove it from the graph.
741 DAG.DeleteNode(N);
742 }
Dan Gohman475871a2008-07-27 21:46:04 +0000743 return SDValue(N, 0);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000744}
745
Evan Chenge5b51ac2010-04-17 06:13:15 +0000746void DAGCombiner::
747CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000748 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000749 // are deleted, make sure to remove them from our worklist.
750 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000751 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000752
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000753 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greifba36cb52008-08-28 21:40:38 +0000754 AddToWorkList(TLO.New.getNode());
755 AddUsersToWorkList(TLO.New.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000756
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000757 // Finally, if the node is now dead, remove it from the graph. The node
758 // may not be dead if the replacement process recursively simplified to
759 // something else needing this node.
Gabor Greifba36cb52008-08-28 21:40:38 +0000760 if (TLO.Old.getNode()->use_empty()) {
761 removeFromWorkList(TLO.Old.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000762
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000763 // If the operands of this node are only used by the node, they will now
764 // be dead. Make sure to visit them first to delete dead nodes early.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700765 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) {
766 SDNode *Op = TLO.Old.getNode()->getOperand(i).getNode();
767 // For an operand generating multiple values, one of the values may
768 // become dead allowing further simplification (e.g. split index
769 // arithmetic from an indexed load).
770 if (Op->hasOneUse() || Op->getNumValues() > 1)
771 AddToWorkList(Op);
772 }
Gabor Greifba36cb52008-08-28 21:40:38 +0000773 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000774 }
Dan Gohmane5af2d32009-01-29 01:59:02 +0000775}
776
777/// SimplifyDemandedBits - Check the specified integer node value to see if
778/// it can be simplified or if things it uses can be simplified by bit
779/// propagation. If so, return true.
780bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000781 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane5af2d32009-01-29 01:59:02 +0000782 APInt KnownZero, KnownOne;
783 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
784 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +0000785
Dan Gohmane5af2d32009-01-29 01:59:02 +0000786 // Revisit the node.
787 AddToWorkList(Op.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +0000788
Dan Gohmane5af2d32009-01-29 01:59:02 +0000789 // Replace the old value with the new one.
790 ++NodesCombined;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000791 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000792 TLO.Old.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000793 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000794 TLO.New.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +0000795 dbgs() << '\n');
Scott Michelfdc40a02009-02-17 22:15:04 +0000796
Dan Gohmane5af2d32009-01-29 01:59:02 +0000797 CommitTargetLoweringOpt(TLO);
Chris Lattnerf8dc0612008-02-03 06:49:24 +0000798 return true;
799}
800
Evan Cheng95c57ea2010-04-24 04:43:44 +0000801void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickac6d9be2013-05-25 02:42:55 +0000802 SDLoc dl(Load);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000803 EVT VT = Load->getValueType(0);
804 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Cheng4c26e932010-04-19 19:29:22 +0000805
Evan Cheng95c57ea2010-04-24 04:43:44 +0000806 DEBUG(dbgs() << "\nReplacing.9 ";
807 Load->dump(&DAG);
808 dbgs() << "\nWith: ";
809 Trunc.getNode()->dump(&DAG);
810 dbgs() << '\n');
811 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +0000812 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
813 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng95c57ea2010-04-24 04:43:44 +0000814 removeFromWorkList(Load);
815 DAG.DeleteNode(Load);
Evan Chengac7eae52010-04-27 19:48:13 +0000816 AddToWorkList(Trunc.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000817}
818
819SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
820 Replace = false;
Andrew Trickac6d9be2013-05-25 02:42:55 +0000821 SDLoc dl(Op);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000822 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chengac7eae52010-04-27 19:48:13 +0000823 EVT MemVT = LD->getMemoryVT();
824 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +0000825 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +0000826 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +0000827 : LD->getExtensionType();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000828 Replace = true;
Stuart Hastingsa9011292011-02-16 16:23:55 +0000829 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000830 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +0000831 MemVT, LD->getMemOperand());
Evan Chenge5b51ac2010-04-17 06:13:15 +0000832 }
833
Evan Cheng4c26e932010-04-19 19:29:22 +0000834 unsigned Opc = Op.getOpcode();
Evan Chengcaf77402010-04-23 19:10:30 +0000835 switch (Opc) {
836 default: break;
837 case ISD::AssertSext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000838 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000839 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000840 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000841 case ISD::AssertZext:
Evan Cheng4c26e932010-04-19 19:29:22 +0000842 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000843 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Cheng4c26e932010-04-19 19:29:22 +0000844 Op.getOperand(1));
Evan Chengcaf77402010-04-23 19:10:30 +0000845 case ISD::Constant: {
846 unsigned ExtOpc =
Evan Cheng4c26e932010-04-19 19:29:22 +0000847 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengcaf77402010-04-23 19:10:30 +0000848 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000849 }
Evan Chengcaf77402010-04-23 19:10:30 +0000850 }
851
852 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chenge5b51ac2010-04-17 06:13:15 +0000853 return SDValue();
Evan Chengcaf77402010-04-23 19:10:30 +0000854 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000855}
856
Evan Cheng95c57ea2010-04-24 04:43:44 +0000857SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000858 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
859 return SDValue();
860 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000861 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000862 bool Replace = false;
863 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700864 if (!NewOp.getNode())
Evan Chenge5b51ac2010-04-17 06:13:15 +0000865 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000866 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000867
868 if (Replace)
869 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
870 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chenge5b51ac2010-04-17 06:13:15 +0000871 DAG.getValueType(OldVT));
872}
873
Evan Cheng95c57ea2010-04-24 04:43:44 +0000874SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chenge5b51ac2010-04-17 06:13:15 +0000875 EVT OldVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +0000876 SDLoc dl(Op);
Evan Cheng95c57ea2010-04-24 04:43:44 +0000877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700879 if (!NewOp.getNode())
Evan Chenge5b51ac2010-04-17 06:13:15 +0000880 return SDValue();
Evan Chengac7eae52010-04-27 19:48:13 +0000881 AddToWorkList(NewOp.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000882
883 if (Replace)
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000886}
887
Evan Cheng64b7bf72010-04-16 06:14:10 +0000888/// PromoteIntBinOp - Promote the specified integer binary operation if the
889/// target indicates it is beneficial. e.g. On x86, it's usually better to
890/// promote i16 operations to i32 since i16 instructions are longer.
891SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
892 if (!LegalOperations)
893 return SDValue();
894
895 EVT VT = Op.getValueType();
896 if (VT.isVector() || !VT.isInteger())
897 return SDValue();
898
Evan Chenge5b51ac2010-04-17 06:13:15 +0000899 // If operation type is 'undesirable', e.g. i16 on x86, consider
900 // promoting it.
901 unsigned Opc = Op.getOpcode();
902 if (TLI.isTypeDesirableForOp(Opc, VT))
903 return SDValue();
904
Evan Cheng64b7bf72010-04-16 06:14:10 +0000905 EVT PVT = VT;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000906 // Consult target whether it is a good idea to promote this operation and
907 // what's the right type to promote it to.
908 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Cheng64b7bf72010-04-16 06:14:10 +0000909 assert(PVT != VT && "Don't know what type to promote to!");
910
Evan Cheng95c57ea2010-04-24 04:43:44 +0000911 bool Replace0 = false;
912 SDValue N0 = Op.getOperand(0);
913 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700914 if (!NN0.getNode())
Evan Cheng07c4e102010-04-22 20:19:46 +0000915 return SDValue();
916
Evan Cheng95c57ea2010-04-24 04:43:44 +0000917 bool Replace1 = false;
918 SDValue N1 = Op.getOperand(1);
Evan Chengaad753b2010-05-10 19:03:57 +0000919 SDValue NN1;
920 if (N0 == N1)
921 NN1 = NN0;
922 else {
923 NN1 = PromoteOperand(N1, PVT, Replace1);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700924 if (!NN1.getNode())
Evan Chengaad753b2010-05-10 19:03:57 +0000925 return SDValue();
926 }
Evan Cheng07c4e102010-04-22 20:19:46 +0000927
Evan Cheng95c57ea2010-04-24 04:43:44 +0000928 AddToWorkList(NN0.getNode());
Evan Chengaad753b2010-05-10 19:03:57 +0000929 if (NN1.getNode())
930 AddToWorkList(NN1.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000931
932 if (Replace0)
933 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
934 if (Replace1)
935 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Cheng07c4e102010-04-22 20:19:46 +0000936
Evan Chengac7eae52010-04-27 19:48:13 +0000937 DEBUG(dbgs() << "\nPromoting ";
938 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000939 SDLoc dl(Op);
Evan Cheng07c4e102010-04-22 20:19:46 +0000940 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng95c57ea2010-04-24 04:43:44 +0000941 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Cheng07c4e102010-04-22 20:19:46 +0000942 }
943 return SDValue();
944}
945
946/// PromoteIntShiftOp - Promote the specified integer shift operation if the
947/// target indicates it is beneficial. e.g. On x86, it's usually better to
948/// promote i16 operations to i32 since i16 instructions are longer.
949SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
950 if (!LegalOperations)
951 return SDValue();
952
953 EVT VT = Op.getValueType();
954 if (VT.isVector() || !VT.isInteger())
955 return SDValue();
956
957 // If operation type is 'undesirable', e.g. i16 on x86, consider
958 // promoting it.
959 unsigned Opc = Op.getOpcode();
960 if (TLI.isTypeDesirableForOp(Opc, VT))
961 return SDValue();
962
963 EVT PVT = VT;
964 // Consult target whether it is a good idea to promote this operation and
965 // what's the right type to promote it to.
966 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
967 assert(PVT != VT && "Don't know what type to promote to!");
968
Evan Cheng95c57ea2010-04-24 04:43:44 +0000969 bool Replace = false;
Evan Chenge5b51ac2010-04-17 06:13:15 +0000970 SDValue N0 = Op.getOperand(0);
971 if (Opc == ISD::SRA)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000972 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000973 else if (Opc == ISD::SRL)
Evan Cheng95c57ea2010-04-24 04:43:44 +0000974 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chenge5b51ac2010-04-17 06:13:15 +0000975 else
Evan Cheng95c57ea2010-04-24 04:43:44 +0000976 N0 = PromoteOperand(N0, PVT, Replace);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700977 if (!N0.getNode())
Evan Chenge5b51ac2010-04-17 06:13:15 +0000978 return SDValue();
Evan Cheng95c57ea2010-04-24 04:43:44 +0000979
Evan Chenge5b51ac2010-04-17 06:13:15 +0000980 AddToWorkList(N0.getNode());
Evan Cheng95c57ea2010-04-24 04:43:44 +0000981 if (Replace)
982 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Cheng64b7bf72010-04-16 06:14:10 +0000983
Evan Chengac7eae52010-04-27 19:48:13 +0000984 DEBUG(dbgs() << "\nPromoting ";
985 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +0000986 SDLoc dl(Op);
Evan Cheng64b7bf72010-04-16 06:14:10 +0000987 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng07c4e102010-04-22 20:19:46 +0000988 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Cheng64b7bf72010-04-16 06:14:10 +0000989 }
990 return SDValue();
991}
992
Evan Cheng4c26e932010-04-19 19:29:22 +0000993SDValue DAGCombiner::PromoteExtend(SDValue Op) {
994 if (!LegalOperations)
995 return SDValue();
996
997 EVT VT = Op.getValueType();
998 if (VT.isVector() || !VT.isInteger())
999 return SDValue();
1000
1001 // If operation type is 'undesirable', e.g. i16 on x86, consider
1002 // promoting it.
1003 unsigned Opc = Op.getOpcode();
1004 if (TLI.isTypeDesirableForOp(Opc, VT))
1005 return SDValue();
1006
1007 EVT PVT = VT;
1008 // Consult target whether it is a good idea to promote this operation and
1009 // what's the right type to promote it to.
1010 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1011 assert(PVT != VT && "Don't know what type to promote to!");
1012 // fold (aext (aext x)) -> (aext x)
1013 // fold (aext (zext x)) -> (zext x)
1014 // fold (aext (sext x)) -> (sext x)
Evan Chengac7eae52010-04-27 19:48:13 +00001015 DEBUG(dbgs() << "\nPromoting ";
1016 Op.getNode()->dump(&DAG));
Andrew Trickac6d9be2013-05-25 02:42:55 +00001017 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Cheng4c26e932010-04-19 19:29:22 +00001018 }
1019 return SDValue();
1020}
1021
1022bool DAGCombiner::PromoteLoad(SDValue Op) {
1023 if (!LegalOperations)
1024 return false;
1025
1026 EVT VT = Op.getValueType();
1027 if (VT.isVector() || !VT.isInteger())
1028 return false;
1029
1030 // If operation type is 'undesirable', e.g. i16 on x86, consider
1031 // promoting it.
1032 unsigned Opc = Op.getOpcode();
1033 if (TLI.isTypeDesirableForOp(Opc, VT))
1034 return false;
1035
1036 EVT PVT = VT;
1037 // Consult target whether it is a good idea to promote this operation and
1038 // what's the right type to promote it to.
1039 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1040 assert(PVT != VT && "Don't know what type to promote to!");
1041
Andrew Trickac6d9be2013-05-25 02:42:55 +00001042 SDLoc dl(Op);
Evan Cheng4c26e932010-04-19 19:29:22 +00001043 SDNode *N = Op.getNode();
1044 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chengac7eae52010-04-27 19:48:13 +00001045 EVT MemVT = LD->getMemoryVT();
1046 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Anderson95771af2011-02-25 21:41:48 +00001047 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopher503a64d2010-12-09 04:48:06 +00001048 : ISD::EXTLOAD)
Evan Chengac7eae52010-04-27 19:48:13 +00001049 : LD->getExtensionType();
Stuart Hastingsa9011292011-02-16 16:23:55 +00001050 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Cheng4c26e932010-04-19 19:29:22 +00001051 LD->getChain(), LD->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00001052 MemVT, LD->getMemOperand());
Evan Cheng4c26e932010-04-19 19:29:22 +00001053 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1054
Evan Cheng95c57ea2010-04-24 04:43:44 +00001055 DEBUG(dbgs() << "\nPromoting ";
Evan Cheng4c26e932010-04-19 19:29:22 +00001056 N->dump(&DAG);
Evan Cheng95c57ea2010-04-24 04:43:44 +00001057 dbgs() << "\nTo: ";
Evan Cheng4c26e932010-04-19 19:29:22 +00001058 Result.getNode()->dump(&DAG);
1059 dbgs() << '\n');
1060 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001061 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Cheng4c26e932010-04-19 19:29:22 +00001063 removeFromWorkList(N);
1064 DAG.DeleteNode(N);
Evan Chengac7eae52010-04-27 19:48:13 +00001065 AddToWorkList(Result.getNode());
Evan Cheng4c26e932010-04-19 19:29:22 +00001066 return true;
1067 }
1068 return false;
1069}
1070
Evan Chenge5b51ac2010-04-17 06:13:15 +00001071
Chris Lattner29446522007-05-14 22:04:50 +00001072//===----------------------------------------------------------------------===//
1073// Main DAG Combiner implementation
1074//===----------------------------------------------------------------------===//
1075
Duncan Sands25cf2272008-11-24 14:53:14 +00001076void DAGCombiner::Run(CombineLevel AtLevel) {
1077 // set the instance variables, so that the various visit routines may use it.
1078 Level = AtLevel;
Eli Friedman50185242011-11-12 00:35:34 +00001079 LegalOperations = Level >= AfterLegalizeVectorOps;
1080 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman4ebd8052005-09-01 23:24:04 +00001081
Evan Cheng17a568b2008-08-29 22:21:44 +00001082 // Add all the dag nodes to the worklist.
Evan Cheng17a568b2008-08-29 22:21:44 +00001083 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1084 E = DAG.allnodes_end(); I != E; ++I)
James Molloy6660c052012-02-16 09:17:04 +00001085 AddToWorkList(I);
Duncan Sands25cf2272008-11-24 14:53:14 +00001086
Evan Cheng17a568b2008-08-29 22:21:44 +00001087 // Create a dummy node (which is not added to allnodes), that adds a reference
1088 // to the root node, preventing it from being deleted, and tracking any
1089 // changes of the root.
1090 HandleSDNode Dummy(DAG.getRoot());
Scott Michelfdc40a02009-02-17 22:15:04 +00001091
Jim Laskey26f7fa72006-10-17 19:33:52 +00001092 // The root of the dag may dangle to deleted nodes until the dag combiner is
1093 // done. Set it to null to avoid confusion.
Dan Gohman475871a2008-07-27 21:46:04 +00001094 DAG.setRoot(SDValue());
Scott Michelfdc40a02009-02-17 22:15:04 +00001095
James Molloy6660c052012-02-16 09:17:04 +00001096 // while the worklist isn't empty, find a node and
Evan Cheng17a568b2008-08-29 22:21:44 +00001097 // try and combine it.
James Molloy6660c052012-02-16 09:17:04 +00001098 while (!WorkListContents.empty()) {
1099 SDNode *N;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001100 // The WorkListOrder holds the SDNodes in order, but it may contain
1101 // duplicates.
James Molloy6660c052012-02-16 09:17:04 +00001102 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1103 // worklist *should* contain, and check the node we want to visit is should
1104 // actually be visited.
1105 do {
Benjamin Kramerd5f76902012-03-10 00:23:58 +00001106 N = WorkListOrder.pop_back_val();
James Molloy6660c052012-02-16 09:17:04 +00001107 } while (!WorkListContents.erase(N));
Scott Michelfdc40a02009-02-17 22:15:04 +00001108
Evan Cheng17a568b2008-08-29 22:21:44 +00001109 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1110 // N is deleted from the DAG, since they too may now be dead or may have a
1111 // reduced number of uses, allowing other xforms.
1112 if (N->use_empty() && N != &Dummy) {
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1114 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001115
Evan Cheng17a568b2008-08-29 22:21:44 +00001116 DAG.DeleteNode(N);
1117 continue;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001118 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001119
Evan Cheng17a568b2008-08-29 22:21:44 +00001120 SDValue RV = combine(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001121
Stephen Hinesdce4a402014-05-29 02:49:00 -07001122 if (!RV.getNode())
Evan Cheng17a568b2008-08-29 22:21:44 +00001123 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001124
Evan Cheng17a568b2008-08-29 22:21:44 +00001125 ++NodesCombined;
Scott Michelfdc40a02009-02-17 22:15:04 +00001126
Evan Cheng17a568b2008-08-29 22:21:44 +00001127 // If we get back the same node we passed in, rather than a new node or
1128 // zero, we know that the node must have defined multiple values and
Scott Michelfdc40a02009-02-17 22:15:04 +00001129 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng17a568b2008-08-29 22:21:44 +00001130 // mechanics for us, we have no work to do in this case.
1131 if (RV.getNode() == N)
1132 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +00001133
Evan Cheng17a568b2008-08-29 22:21:44 +00001134 assert(N->getOpcode() != ISD::DELETED_NODE &&
1135 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1136 "Node was deleted but visit returned new node!");
Chris Lattner729c6d12006-05-27 00:43:02 +00001137
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001138 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001139 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001140 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001141 RV.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00001142 dbgs() << '\n');
Eric Christopher7332e6e2011-07-14 01:12:15 +00001143
Devang Patel9728ea22011-05-23 22:04:42 +00001144 // Transfer debug value.
1145 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001146 WorkListRemover DeadNodes(*this);
1147 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001148 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng17a568b2008-08-29 22:21:44 +00001149 else {
1150 assert(N->getValueType(0) == RV.getValueType() &&
1151 N->getNumValues() == 1 && "Type mismatch");
1152 SDValue OpV = RV;
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001153 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng17a568b2008-08-29 22:21:44 +00001154 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001155
Evan Cheng17a568b2008-08-29 22:21:44 +00001156 // Push the new node and any users onto the worklist
1157 AddToWorkList(RV.getNode());
1158 AddUsersToWorkList(RV.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001159
Evan Cheng17a568b2008-08-29 22:21:44 +00001160 // Add any uses of the old node to the worklist in case this node is the
1161 // last one that uses them. They may become dead after this node is
1162 // deleted.
1163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1164 AddToWorkList(N->getOperand(i).getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00001165
Dan Gohmandbe664a2009-01-19 21:44:21 +00001166 // Finally, if the node is now dead, remove it from the graph. The node
1167 // may not be dead if the replacement process recursively simplified to
1168 // something else needing this node.
1169 if (N->use_empty()) {
1170 // Nodes can be reintroduced into the worklist. Make sure we do not
1171 // process a node that has been replaced.
1172 removeFromWorkList(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001173
Dan Gohmandbe664a2009-01-19 21:44:21 +00001174 // Finally, since the node is now dead, remove it from the graph.
1175 DAG.DeleteNode(N);
1176 }
Evan Cheng17a568b2008-08-29 22:21:44 +00001177 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001178
Chris Lattner95038592005-10-05 06:35:28 +00001179 // If the root changed (e.g. it was a dead load, update the root).
1180 DAG.setRoot(Dummy.getValue());
Hal Finkel31490ba2012-04-16 03:33:22 +00001181 DAG.RemoveDeadNodes();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001182}
1183
Dan Gohman475871a2008-07-27 21:46:04 +00001184SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001185 switch (N->getOpcode()) {
Nate Begeman1d4d4142005-09-01 00:19:25 +00001186 default: break;
Nate Begeman4942a962005-09-01 00:33:32 +00001187 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001188 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001189 case ISD::ADD: return visitADD(N);
1190 case ISD::SUB: return visitSUB(N);
Chris Lattner91153682007-03-04 20:03:15 +00001191 case ISD::ADDC: return visitADDC(N);
Craig Toppercc274522012-01-07 09:06:39 +00001192 case ISD::SUBC: return visitSUBC(N);
Chris Lattner91153682007-03-04 20:03:15 +00001193 case ISD::ADDE: return visitADDE(N);
Craig Toppercc274522012-01-07 09:06:39 +00001194 case ISD::SUBE: return visitSUBE(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001195 case ISD::MUL: return visitMUL(N);
1196 case ISD::SDIV: return visitSDIV(N);
1197 case ISD::UDIV: return visitUDIV(N);
1198 case ISD::SREM: return visitSREM(N);
1199 case ISD::UREM: return visitUREM(N);
1200 case ISD::MULHU: return visitMULHU(N);
1201 case ISD::MULHS: return visitMULHS(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001202 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1203 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00001204 case ISD::SMULO: return visitSMULO(N);
1205 case ISD::UMULO: return visitUMULO(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001206 case ISD::SDIVREM: return visitSDIVREM(N);
1207 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001208 case ISD::AND: return visitAND(N);
1209 case ISD::OR: return visitOR(N);
1210 case ISD::XOR: return visitXOR(N);
1211 case ISD::SHL: return visitSHL(N);
1212 case ISD::SRA: return visitSRA(N);
1213 case ISD::SRL: return visitSRL(N);
Stephen Hines36b56882014-04-23 16:57:46 -07001214 case ISD::ROTR:
1215 case ISD::ROTL: return visitRotate(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001216 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001217 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001218 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth63974b22011-12-13 01:56:10 +00001219 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001220 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001221 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00001222 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman452d7be2005-09-16 00:54:12 +00001223 case ISD::SELECT_CC: return visitSELECT_CC(N);
1224 case ISD::SETCC: return visitSETCC(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001225 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1226 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner5ffc0662006-05-05 05:58:59 +00001227 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001228 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1229 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001230 case ISD::BITCAST: return visitBITCAST(N);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00001231 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001232 case ISD::FADD: return visitFADD(N);
1233 case ISD::FSUB: return visitFSUB(N);
1234 case ISD::FMUL: return visitFMUL(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00001235 case ISD::FMA: return visitFMA(N);
Chris Lattner01b3d732005-09-28 22:28:18 +00001236 case ISD::FDIV: return visitFDIV(N);
1237 case ISD::FREM: return visitFREM(N);
Chris Lattner12d83032006-03-05 05:30:57 +00001238 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman646d7e22005-09-02 21:18:40 +00001239 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1240 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1241 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1242 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1243 case ISD::FP_ROUND: return visitFP_ROUND(N);
1244 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1245 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1246 case ISD::FNEG: return visitFNEG(N);
1247 case ISD::FABS: return visitFABS(N);
Owen Anderson7c626d32012-08-13 23:32:49 +00001248 case ISD::FFLOOR: return visitFFLOOR(N);
1249 case ISD::FCEIL: return visitFCEIL(N);
1250 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001251 case ISD::BRCOND: return visitBRCOND(N);
Nate Begeman44728a72005-09-19 22:34:01 +00001252 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattner01a22022005-10-10 22:04:48 +00001253 case ISD::LOAD: return visitLOAD(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00001254 case ISD::STORE: return visitSTORE(N);
Chris Lattnerca242442006-03-19 01:27:56 +00001255 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng513da432007-10-06 08:19:55 +00001256 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohman7f321562007-06-25 16:23:39 +00001257 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1258 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +00001259 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattner66445d32006-03-28 22:11:53 +00001260 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Stephen Hines36b56882014-04-23 16:57:46 -07001261 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001262 }
Dan Gohman475871a2008-07-27 21:46:04 +00001263 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001264}
1265
Dan Gohman475871a2008-07-27 21:46:04 +00001266SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00001267 SDValue RV = visit(N);
Dan Gohman389079b2007-10-08 17:57:15 +00001268
1269 // If nothing happened, try a target-specific DAG combine.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001270 if (!RV.getNode()) {
Dan Gohman389079b2007-10-08 17:57:15 +00001271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 "Node was deleted but visit returned NULL!");
1273
1274 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1275 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1276
1277 // Expose the DAG combiner to the target combiner impls.
Scott Michelfdc40a02009-02-17 22:15:04 +00001278 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +00001279 DagCombineInfo(DAG, Level, false, this);
Dan Gohman389079b2007-10-08 17:57:15 +00001280
1281 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1282 }
1283 }
1284
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001285 // If nothing happened still, try promoting the operation.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001286 if (!RV.getNode()) {
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001287 switch (N->getOpcode()) {
1288 default: break;
1289 case ISD::ADD:
1290 case ISD::SUB:
1291 case ISD::MUL:
1292 case ISD::AND:
1293 case ISD::OR:
1294 case ISD::XOR:
1295 RV = PromoteIntBinOp(SDValue(N, 0));
1296 break;
1297 case ISD::SHL:
1298 case ISD::SRA:
1299 case ISD::SRL:
1300 RV = PromoteIntShiftOp(SDValue(N, 0));
1301 break;
1302 case ISD::SIGN_EXTEND:
1303 case ISD::ZERO_EXTEND:
1304 case ISD::ANY_EXTEND:
1305 RV = PromoteExtend(SDValue(N, 0));
1306 break;
1307 case ISD::LOAD:
1308 if (PromoteLoad(SDValue(N, 0)))
1309 RV = SDValue(N, 0);
1310 break;
1311 }
1312 }
1313
Scott Michelfdc40a02009-02-17 22:15:04 +00001314 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng08b11732008-03-22 01:55:50 +00001315 // sdisel CSE.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001316 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng08b11732008-03-22 01:55:50 +00001317 N->getNumValues() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00001318 SDValue N0 = N->getOperand(0);
1319 SDValue N1 = N->getOperand(1);
Bill Wendling5c71acf2009-01-30 01:13:16 +00001320
Evan Cheng08b11732008-03-22 01:55:50 +00001321 // Constant operands are canonicalized to RHS.
1322 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001323 SDValue Ops[] = { N1, N0 };
Evan Cheng08b11732008-03-22 01:55:50 +00001324 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
Stephen Hinesdce4a402014-05-29 02:49:00 -07001325 Ops);
Evan Chengea100462008-03-24 23:55:16 +00001326 if (CSENode)
Dan Gohman475871a2008-07-27 21:46:04 +00001327 return SDValue(CSENode, 0);
Evan Cheng08b11732008-03-22 01:55:50 +00001328 }
1329 }
1330
Dan Gohman389079b2007-10-08 17:57:15 +00001331 return RV;
Scott Michelfdc40a02009-02-17 22:15:04 +00001332}
Dan Gohman389079b2007-10-08 17:57:15 +00001333
Chris Lattner6270f682006-10-08 22:57:01 +00001334/// getInputChainForNode - Given a node, return its input chain if it has one,
1335/// otherwise return a null sd operand.
Dan Gohman475871a2008-07-27 21:46:04 +00001336static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001337 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001338 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001339 return N->getOperand(0);
Stephen Linb4940152013-07-09 00:44:49 +00001340 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001341 return N->getOperand(NumOps-1);
1342 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +00001343 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner6270f682006-10-08 22:57:01 +00001344 return N->getOperand(i);
1345 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001346 return SDValue();
Chris Lattner6270f682006-10-08 22:57:01 +00001347}
1348
Dan Gohman475871a2008-07-27 21:46:04 +00001349SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner6270f682006-10-08 22:57:01 +00001350 // If N has two operands, where one has an input chain equal to the other,
1351 // the 'other' chain is redundant.
1352 if (N->getNumOperands() == 2) {
Gabor Greifba36cb52008-08-28 21:40:38 +00001353 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner6270f682006-10-08 22:57:01 +00001354 return N->getOperand(0);
Gabor Greifba36cb52008-08-28 21:40:38 +00001355 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner6270f682006-10-08 22:57:01 +00001356 return N->getOperand(1);
1357 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001358
Chris Lattnerc76d4412007-05-16 06:37:59 +00001359 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman475871a2008-07-27 21:46:04 +00001360 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001361 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattnerc76d4412007-05-16 06:37:59 +00001362 bool Changed = false; // If we should replace this token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001363
Jim Laskey6ff23e52006-10-04 16:53:27 +00001364 // Start out with this token factor.
Jim Laskey279f0532006-09-25 16:29:54 +00001365 TFs.push_back(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00001366
Jim Laskey71382342006-10-07 23:37:56 +00001367 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskeybc588b82006-10-05 15:07:25 +00001368 // encountered.
1369 for (unsigned i = 0; i < TFs.size(); ++i) {
1370 SDNode *TF = TFs[i];
Scott Michelfdc40a02009-02-17 22:15:04 +00001371
Jim Laskey6ff23e52006-10-04 16:53:27 +00001372 // Check each of the operands.
1373 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001374 SDValue Op = TF->getOperand(i);
Scott Michelfdc40a02009-02-17 22:15:04 +00001375
Jim Laskey6ff23e52006-10-04 16:53:27 +00001376 switch (Op.getOpcode()) {
1377 case ISD::EntryToken:
Jim Laskeybc588b82006-10-05 15:07:25 +00001378 // Entry tokens don't need to be added to the list. They are
1379 // rededundant.
1380 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001381 break;
Scott Michelfdc40a02009-02-17 22:15:04 +00001382
Jim Laskey6ff23e52006-10-04 16:53:27 +00001383 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +00001384 if (Op.hasOneUse() &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001385 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001386 // Queue up for processing.
Gabor Greifba36cb52008-08-28 21:40:38 +00001387 TFs.push_back(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001388 // Clean up in case the token factor is removed.
Gabor Greifba36cb52008-08-28 21:40:38 +00001389 AddToWorkList(Op.getNode());
Jim Laskey6ff23e52006-10-04 16:53:27 +00001390 Changed = true;
1391 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001392 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001393 // Fall thru
Scott Michelfdc40a02009-02-17 22:15:04 +00001394
Jim Laskey6ff23e52006-10-04 16:53:27 +00001395 default:
Chris Lattnerc76d4412007-05-16 06:37:59 +00001396 // Only add if it isn't already in the list.
Gabor Greifba36cb52008-08-28 21:40:38 +00001397 if (SeenOps.insert(Op.getNode()))
Jim Laskeybc588b82006-10-05 15:07:25 +00001398 Ops.push_back(Op);
Chris Lattnerc76d4412007-05-16 06:37:59 +00001399 else
1400 Changed = true;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001401 break;
Jim Laskey279f0532006-09-25 16:29:54 +00001402 }
1403 }
Jim Laskey6ff23e52006-10-04 16:53:27 +00001404 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001405
Dan Gohman475871a2008-07-27 21:46:04 +00001406 SDValue Result;
Jim Laskey6ff23e52006-10-04 16:53:27 +00001407
1408 // If we've change things around then replace token factor.
1409 if (Changed) {
Dan Gohman30359592008-01-29 13:02:09 +00001410 if (Ops.empty()) {
Jim Laskey6ff23e52006-10-04 16:53:27 +00001411 // The entry token is the only possible outcome.
1412 Result = DAG.getEntryNode();
1413 } else {
1414 // New and improved token factor.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001415 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begemanded49632005-10-13 03:11:28 +00001416 }
Bill Wendling5c71acf2009-01-30 01:13:16 +00001417
Jim Laskey274062c2006-10-13 23:32:28 +00001418 // Don't add users to work list.
1419 return CombineTo(N, Result, false);
Nate Begemanded49632005-10-13 03:11:28 +00001420 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001421
Jim Laskey6ff23e52006-10-04 16:53:27 +00001422 return Result;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001423}
1424
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001425/// MERGE_VALUES can always be eliminated.
Dan Gohman475871a2008-07-27 21:46:04 +00001426SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001427 WorkListRemover DeadNodes(*this);
Dan Gohman00edf392009-08-10 23:43:19 +00001428 // Replacing results may cause a different MERGE_VALUES to suddenly
1429 // be CSE'd with N, and carry its uses with it. Iterate until no
1430 // uses remain, to ensure that the node can be safely deleted.
Pete Cooper3affd9e2012-06-20 19:35:43 +00001431 // First add the users of this node to the work list so that they
1432 // can be tried again once they have new operands.
1433 AddUsersToWorkList(N);
Dan Gohman00edf392009-08-10 23:43:19 +00001434 do {
1435 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00001436 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman00edf392009-08-10 23:43:19 +00001437 } while (!N->use_empty());
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001438 removeFromWorkList(N);
1439 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00001440 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnerfec42eb2008-02-13 07:25:05 +00001441}
1442
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001443static
Andrew Trickac6d9be2013-05-25 02:42:55 +00001444SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001445 SelectionDAG &DAG) {
Owen Andersone50ed302009-08-10 22:56:29 +00001446 EVT VT = N0.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001447 SDValue N00 = N0.getOperand(0);
1448 SDValue N01 = N0.getOperand(1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001449 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingd69c3142009-01-30 02:23:43 +00001450
Gabor Greifba36cb52008-08-28 21:40:38 +00001451 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001452 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingd69c3142009-01-30 02:23:43 +00001453 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickac6d9be2013-05-25 02:42:55 +00001454 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1455 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001456 N00.getOperand(0), N01),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001457 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingd69c3142009-01-30 02:23:43 +00001458 N00.getOperand(1), N01));
1459 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001460 }
Bill Wendlingd69c3142009-01-30 02:23:43 +00001461
Dan Gohman475871a2008-07-27 21:46:04 +00001462 return SDValue();
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001463}
1464
Dan Gohman475871a2008-07-27 21:46:04 +00001465SDValue DAGCombiner::visitADD(SDNode *N) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00001468 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1469 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001470 EVT VT = N0.getValueType();
Dan Gohman7f321562007-06-25 16:23:39 +00001471
1472 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001473 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001474 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001475 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001476
1477 // fold (add x, 0) -> x, vector edition
1478 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1479 return N0;
1480 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1481 return N1;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001482 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001483
Dan Gohman613e0d82007-07-03 14:03:57 +00001484 // fold (add x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001485 if (N0.getOpcode() == ISD::UNDEF)
1486 return N0;
1487 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001488 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001489 // fold (add c1, c2) -> c1+c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001490 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001491 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00001492 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00001493 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001494 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001495 // fold (add x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00001496 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00001497 return N0;
Dan Gohman6520e202008-10-18 02:06:02 +00001498 // fold (add Sym, c) -> Sym+c
1499 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001500 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman6520e202008-10-18 02:06:02 +00001501 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001502 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001503 GA->getOffset() +
1504 (uint64_t)N1C->getSExtValue());
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001505 // fold ((c1-A)+c2) -> (c1+c2)-A
1506 if (N1C && N0.getOpcode() == ISD::SUB)
1507 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001508 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohman002e5d02008-03-13 22:13:53 +00001509 DAG.getConstant(N1C->getAPIntValue()+
1510 N0C->getAPIntValue(), VT),
Chris Lattner4aafb4f2006-01-12 20:22:43 +00001511 N0.getOperand(1));
Nate Begemancd4d58c2006-02-03 06:46:56 +00001512 // reassociate add
Andrew Trickac6d9be2013-05-25 02:42:55 +00001513 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001514 if (RADD.getNode())
Nate Begemancd4d58c2006-02-03 06:46:56 +00001515 return RADD;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001516 // fold ((0-A) + B) -> B-A
1517 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1518 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001519 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman1d4d4142005-09-01 00:19:25 +00001520 // fold (A + (0-B)) -> A-B
1521 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1522 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00001524 // fold (A+(B-A)) -> B
1525 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begeman83e75ec2005-09-06 04:43:02 +00001526 return N1.getOperand(0);
Dale Johannesen56eca912008-11-27 00:43:21 +00001527 // fold ((B-A)+A) -> B
1528 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1529 return N0.getOperand(0);
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001530 // fold (A+(B-(A+C))) to (B-C)
1531 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001532 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001534 N1.getOperand(1).getOperand(1));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001535 // fold (A+(B-(C+A))) to (B-C)
1536 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001537 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001538 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001539 N1.getOperand(1).getOperand(0));
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001540 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen34d79852008-12-02 18:40:40 +00001541 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1542 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001543 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001544 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001545 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen34d79852008-12-02 18:40:40 +00001546
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001547 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1548 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1549 SDValue N00 = N0.getOperand(0);
1550 SDValue N01 = N0.getOperand(1);
1551 SDValue N10 = N1.getOperand(0);
1552 SDValue N11 = N1.getOperand(1);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001553
1554 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001555 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1556 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1557 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen221cd2f2008-12-02 01:30:54 +00001558 }
Chris Lattner947c2892006-03-13 06:51:27 +00001559
Dan Gohman475871a2008-07-27 21:46:04 +00001560 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1561 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001562
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001563 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001564 if (VT.isInteger() && !VT.isVector()) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00001565 APInt LHSZero, LHSOne;
1566 APInt RHSZero, RHSOne;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001567 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingf4eb2262009-01-30 02:31:17 +00001568
Dan Gohman948d8ea2008-02-20 16:33:30 +00001569 if (LHSZero.getBoolValue()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001570 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001571
Chris Lattner947c2892006-03-13 06:51:27 +00001572 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1573 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Stephen Hines36b56882014-04-23 16:57:46 -07001574 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1575 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1576 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1577 }
Chris Lattner947c2892006-03-13 06:51:27 +00001578 }
1579 }
Evan Cheng3ef554d2006-11-06 08:14:30 +00001580
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001581 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greifba36cb52008-08-28 21:40:38 +00001582 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001583 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001584 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001585 }
Gabor Greifba36cb52008-08-28 21:40:38 +00001586 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001587 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greifba36cb52008-08-28 21:40:38 +00001588 if (Result.getNode()) return Result;
Evan Cheng42d7ccf2007-01-19 17:51:44 +00001589 }
1590
Dan Gohmancd9e1552010-01-19 23:30:49 +00001591 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1592 if (N1.getOpcode() == ISD::SHL &&
1593 N1.getOperand(0).getOpcode() == ISD::SUB)
1594 if (ConstantSDNode *C =
1595 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1596 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001597 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1598 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001599 N1.getOperand(0).getOperand(1),
1600 N1.getOperand(1)));
1601 if (N0.getOpcode() == ISD::SHL &&
1602 N0.getOperand(0).getOpcode() == ISD::SUB)
1603 if (ConstantSDNode *C =
1604 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1605 if (C->getAPIntValue() == 0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001606 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1607 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohmancd9e1552010-01-19 23:30:49 +00001608 N0.getOperand(0).getOperand(1),
1609 N0.getOperand(1)));
1610
Owen Andersonbc146b02010-09-21 20:42:50 +00001611 if (N1.getOpcode() == ISD::AND) {
1612 SDValue AndOp0 = N1.getOperand(0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001613 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Andersonbc146b02010-09-21 20:42:50 +00001614 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1615 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00001616
Owen Andersonbc146b02010-09-21 20:42:50 +00001617 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1618 // and similar xforms where the inner op is either ~0 or 0.
1619 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001620 SDLoc DL(N);
Owen Andersonbc146b02010-09-21 20:42:50 +00001621 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1622 }
1623 }
1624
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001625 // add (sext i1), X -> sub X, (zext i1)
1626 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1627 N0.getOperand(0).getValueType() == MVT::i1 &&
1628 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001629 SDLoc DL(N);
Benjamin Kramerf50125e2010-12-22 23:17:45 +00001630 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1631 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1632 }
1633
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001634 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001635}
1636
Dan Gohman475871a2008-07-27 21:46:04 +00001637SDValue DAGCombiner::visitADDC(SDNode *N) {
1638 SDValue N0 = N->getOperand(0);
1639 SDValue N1 = N->getOperand(1);
Chris Lattner91153682007-03-04 20:03:15 +00001640 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1641 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001642 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001643
Chris Lattner91153682007-03-04 20:03:15 +00001644 // If the flag result is dead, turn this into an ADD.
Craig Topper704e1a02012-01-07 18:31:09 +00001645 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001646 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001647 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001648 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001649
Chris Lattner91153682007-03-04 20:03:15 +00001650 // canonicalize constant to RHS.
Dan Gohman0a4627d2008-06-23 15:29:14 +00001651 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001652 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00001653
Chris Lattnerb6541762007-03-04 20:40:38 +00001654 // fold (addc x, 0) -> x + no carry out
1655 if (N1C && N1C->isNullValue())
Dale Johannesen874ae252009-06-02 03:12:52 +00001656 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001657 SDLoc(N), MVT::Glue));
Scott Michelfdc40a02009-02-17 22:15:04 +00001658
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001659 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohman948d8ea2008-02-20 16:33:30 +00001660 APInt LHSZero, LHSOne;
1661 APInt RHSZero, RHSOne;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001662 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling14036c02009-01-30 02:38:00 +00001663
Dan Gohman948d8ea2008-02-20 16:33:30 +00001664 if (LHSZero.getBoolValue()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001665 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00001666
Chris Lattnerb6541762007-03-04 20:40:38 +00001667 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1668 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001669 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001670 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen874ae252009-06-02 03:12:52 +00001671 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001672 SDLoc(N), MVT::Glue));
Chris Lattnerb6541762007-03-04 20:40:38 +00001673 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001674
Dan Gohman475871a2008-07-27 21:46:04 +00001675 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001676}
1677
Dan Gohman475871a2008-07-27 21:46:04 +00001678SDValue DAGCombiner::visitADDE(SDNode *N) {
1679 SDValue N0 = N->getOperand(0);
1680 SDValue N1 = N->getOperand(1);
1681 SDValue CarryIn = N->getOperand(2);
Chris Lattner91153682007-03-04 20:03:15 +00001682 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1683 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001684
Chris Lattner91153682007-03-04 20:03:15 +00001685 // canonicalize constant to RHS
Dan Gohman0a4627d2008-06-23 15:29:14 +00001686 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001687 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling14036c02009-01-30 02:38:00 +00001688 N1, N0, CarryIn);
Scott Michelfdc40a02009-02-17 22:15:04 +00001689
Chris Lattnerb6541762007-03-04 20:40:38 +00001690 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen874ae252009-06-02 03:12:52 +00001691 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001692 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00001693
Dan Gohman475871a2008-07-27 21:46:04 +00001694 return SDValue();
Chris Lattner91153682007-03-04 20:03:15 +00001695}
1696
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001697// Since it may not be valid to emit a fold to zero for vector initializers
1698// check if we can before folding.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001699static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001700 SelectionDAG &DAG,
1701 bool LegalOperations, bool LegalTypes) {
Stephen Linb4940152013-07-09 00:44:49 +00001702 if (!VT.isVector())
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001703 return DAG.getConstant(0, VT);
Daniel Sanders975e9582013-11-25 15:53:39 +00001704 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1705 return DAG.getConstant(0, VT);
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001706 return SDValue();
1707}
1708
Dan Gohman475871a2008-07-27 21:46:04 +00001709SDValue DAGCombiner::visitSUB(SDNode *N) {
1710 SDValue N0 = N->getOperand(0);
1711 SDValue N1 = N->getOperand(1);
Gabor Greifba36cb52008-08-28 21:40:38 +00001712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Stephen Hinesdce4a402014-05-29 02:49:00 -07001714 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopher7332e6e2011-07-14 01:12:15 +00001715 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Andersone50ed302009-08-10 22:56:29 +00001716 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001717
Dan Gohman7f321562007-06-25 16:23:39 +00001718 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001719 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001720 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001721 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper48b509c2012-12-10 08:12:29 +00001722
1723 // fold (sub x, 0) -> x, vector edition
1724 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1725 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001726 }
Bill Wendling2476e5d2008-12-10 22:36:00 +00001727
Chris Lattner854077d2005-10-17 01:07:11 +00001728 // fold (sub x, x) -> 0
Eric Christopher169e1552011-02-16 01:10:03 +00001729 // FIXME: Refactor this and xor and other similar operations together.
Eric Christopher7bccf6a2011-02-16 04:50:12 +00001730 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00001731 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001732 // fold (sub c1, c2) -> c1-c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001733 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001734 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattner05b57432005-10-11 06:07:15 +00001735 // fold (sub x, c) -> (add x, -c)
1736 if (N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001737 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00001738 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng1ad0e8b2010-01-18 21:38:44 +00001739 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1740 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001741 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer2c94b422011-01-29 12:34:05 +00001742 // fold A-(A-B) -> B
1743 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1744 return N1.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001745 // fold (A+B)-A -> B
Chris Lattner01b3d732005-09-28 22:28:18 +00001746 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001747 return N0.getOperand(1);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001748 // fold (A+B)-B -> A
Chris Lattner01b3d732005-09-28 22:28:18 +00001749 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelfdc40a02009-02-17 22:15:04 +00001750 return N0.getOperand(0);
Eric Christopher7332e6e2011-07-14 01:12:15 +00001751 // fold C2-(A+C1) -> (C2-C1)-A
1752 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00001753 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1754 VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001755 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendling96cb1122012-07-19 00:04:14 +00001756 N1.getOperand(0));
Eric Christopher7332e6e2011-07-14 01:12:15 +00001757 }
Dale Johannesen7c7bc722008-12-23 23:47:22 +00001758 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001759 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001760 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1761 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenfd3b7b72008-12-16 22:13:49 +00001762 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001763 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001764 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenf9cbc1f2008-12-23 23:01:27 +00001765 // fold ((A+(C+B))-B) -> A+C
1766 if (N0.getOpcode() == ISD::ADD &&
1767 N0.getOperand(1).getOpcode() == ISD::ADD &&
1768 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001769 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001770 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesen58e39b02008-12-23 01:59:54 +00001771 // fold ((A-(B-C))-C) -> A-B
1772 if (N0.getOpcode() == ISD::SUB &&
1773 N0.getOperand(1).getOpcode() == ISD::SUB &&
1774 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001775 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendlingb0702e02009-01-30 02:42:10 +00001776 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendlingb0702e02009-01-30 02:42:10 +00001777
Dan Gohman613e0d82007-07-03 14:03:57 +00001778 // If either operand of a sub is undef, the result is undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00001779 if (N0.getOpcode() == ISD::UNDEF)
1780 return N0;
1781 if (N1.getOpcode() == ISD::UNDEF)
1782 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00001783
Dan Gohman6520e202008-10-18 02:06:02 +00001784 // If the relocation model supports it, consider symbol offsets.
1785 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sands25cf2272008-11-24 14:53:14 +00001786 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman6520e202008-10-18 02:06:02 +00001787 // fold (sub Sym, c) -> Sym-c
1788 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001789 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman6520e202008-10-18 02:06:02 +00001790 GA->getOffset() -
1791 (uint64_t)N1C->getSExtValue());
1792 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1793 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1794 if (GA->getGlobal() == GB->getGlobal())
1795 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1796 VT);
1797 }
1798
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001799 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001800}
1801
Craig Toppercc274522012-01-07 09:06:39 +00001802SDValue DAGCombiner::visitSUBC(SDNode *N) {
1803 SDValue N0 = N->getOperand(0);
1804 SDValue N1 = N->getOperand(1);
1805 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1807 EVT VT = N0.getValueType();
1808
1809 // If the flag result is dead, turn this into an SUB.
Craig Topper704e1a02012-01-07 18:31:09 +00001810 if (!N->hasAnyUseOfValue(1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001811 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001813 MVT::Glue));
1814
1815 // fold (subc x, x) -> 0 + no borrow
1816 if (N0 == N1)
1817 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001818 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001819 MVT::Glue));
1820
1821 // fold (subc x, 0) -> x + no borrow
1822 if (N1C && N1C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001823 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001824 MVT::Glue));
1825
1826 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1827 if (N0C && N0C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001828 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Toppercc274522012-01-07 09:06:39 +00001830 MVT::Glue));
1831
1832 return SDValue();
1833}
1834
1835SDValue DAGCombiner::visitSUBE(SDNode *N) {
1836 SDValue N0 = N->getOperand(0);
1837 SDValue N1 = N->getOperand(1);
1838 SDValue CarryIn = N->getOperand(2);
1839
1840 // fold (sube x, y, false) -> (subc x, y)
1841 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001842 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Toppercc274522012-01-07 09:06:39 +00001843
1844 return SDValue();
1845}
1846
Dan Gohman475871a2008-07-27 21:46:04 +00001847SDValue DAGCombiner::visitMUL(SDNode *N) {
1848 SDValue N0 = N->getOperand(0);
1849 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00001850 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00001851
Dan Gohman613e0d82007-07-03 14:03:57 +00001852 // fold (mul x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00001853 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00001854 return DAG.getConstant(0, VT);
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001855
1856 bool N0IsConst = false;
1857 bool N1IsConst = false;
1858 APInt ConstValue0, ConstValue1;
1859 // fold vector ops
1860 if (VT.isVector()) {
1861 SDValue FoldedVOp = SimplifyVBinOp(N);
1862 if (FoldedVOp.getNode()) return FoldedVOp;
1863
1864 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1865 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1866 } else {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001867 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001868 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1869 : APInt();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001870 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carteradbd3ae2013-10-17 01:34:33 +00001871 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1872 : APInt();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001873 }
1874
Nate Begeman1d4d4142005-09-01 00:19:25 +00001875 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001876 if (N0IsConst && N1IsConst)
1877 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1878
Nate Begeman99801192005-09-07 23:25:52 +00001879 // canonicalize constant to RHS
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001880 if (N0IsConst && !N1IsConst)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001881 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001882 // fold (mul x, 0) -> 0
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001883 if (N1IsConst && ConstValue1 == 0)
Nate Begeman83e75ec2005-09-06 04:43:02 +00001884 return N1;
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001885 // We require a splat of the entire scalar bit width for non-contiguous
1886 // bit patterns.
1887 bool IsFullSplat =
1888 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001889 // fold (mul x, 1) -> x
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001890 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001891 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00001892 // fold (mul x, -1) -> 0-x
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001893 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001894 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001895 DAG.getConstant(0, VT), N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001896 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001897 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001898 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001899 DAG.getConstant(ConstValue1.logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00001900 getShiftAmountTy(N0.getValueType())));
Chris Lattner3e6099b2005-10-30 06:41:49 +00001901 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramer530d09a2013-09-19 13:28:20 +00001902 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001903 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00001904 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattner3e6099b2005-10-30 06:41:49 +00001905 // single-use add), we should put the negate there.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001906 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001907 DAG.getConstant(0, VT),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001908 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Anderson95771af2011-02-25 21:41:48 +00001909 DAG.getConstant(Log2Val,
1910 getShiftAmountTy(N0.getValueType()))));
Chris Lattner66b8bc32009-03-09 20:22:18 +00001911 }
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001912
1913 APInt Val;
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001914 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lin155615d2013-07-08 00:37:03 +00001915 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001916 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1917 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001918 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001919 N1, N0.getOperand(1));
Gabor Greifba36cb52008-08-28 21:40:38 +00001920 AddToWorkList(C3.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00001921 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001922 N0.getOperand(0), C3);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001923 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001924
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001925 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1926 // use.
1927 {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001928 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001929 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lin155615d2013-07-08 00:37:03 +00001930 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001931 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1932 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00001933 N0.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001934 Sh = N0; Y = N1;
Scott Michelfdc40a02009-02-17 22:15:04 +00001935 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greif12632d22008-08-30 19:29:20 +00001936 isa<ConstantSDNode>(N1.getOperand(1)) &&
1937 N1.getNode()->hasOneUse()) {
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001938 Sh = N1; Y = N0;
1939 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001940
Gabor Greifba36cb52008-08-28 21:40:38 +00001941 if (Sh.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001942 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001943 Sh.getOperand(0), Y);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001944 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001945 Mul, Sh.getOperand(1));
Chris Lattner0b1a85f2006-03-01 03:44:24 +00001946 }
1947 }
Bill Wendling73e16b22009-01-30 02:49:26 +00001948
Chris Lattnera1deca32006-03-04 23:33:26 +00001949 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky87070fe2013-06-26 10:55:03 +00001950 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1951 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1952 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001953 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1954 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001955 N0.getOperand(0), N1),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001956 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling9c8148a2009-01-30 02:45:56 +00001957 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00001958
Nate Begemancd4d58c2006-02-03 06:46:56 +00001959 // reassociate mul
Andrew Trickac6d9be2013-05-25 02:42:55 +00001960 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001961 if (RMUL.getNode())
Nate Begemancd4d58c2006-02-03 06:46:56 +00001962 return RMUL;
Dan Gohman7f321562007-06-25 16:23:39 +00001963
Evan Chengb3a3d5e2010-04-28 07:10:39 +00001964 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00001965}
1966
Dan Gohman475871a2008-07-27 21:46:04 +00001967SDValue DAGCombiner::visitSDIV(SDNode *N) {
1968 SDValue N0 = N->getOperand(0);
1969 SDValue N1 = N->getOperand(1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001970 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1971 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00001972 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00001973
Dan Gohman7f321562007-06-25 16:23:39 +00001974 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00001975 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00001976 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00001977 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00001978 }
Scott Michelfdc40a02009-02-17 22:15:04 +00001979
Nate Begeman1d4d4142005-09-01 00:19:25 +00001980 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00001981 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00001982 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman405e3ec2005-10-21 00:02:42 +00001983 // fold (sdiv X, 1) -> X
Eli Friedmanfd58cd72011-10-27 02:06:39 +00001984 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman405e3ec2005-10-21 00:02:42 +00001985 return N0;
1986 // fold (sdiv X, -1) -> 0-X
1987 if (N1C && N1C->isAllOnesValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00001988 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling944d34b2009-01-30 02:52:17 +00001989 DAG.getConstant(0, VT), N0);
Chris Lattner094c8fc2005-10-07 06:10:46 +00001990 // If we know the sign bits of both operands are zero, strength reduce to a
1991 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands83ec4b62008-06-06 12:08:01 +00001992 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00001993 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001994 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling944d34b2009-01-30 02:52:17 +00001995 N0, N1);
Chris Lattnerf32aac32008-01-27 23:32:17 +00001996 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001997
Nate Begemancd6a6ed2006-02-17 07:26:20 +00001998 // fold (sdiv X, pow2) -> simple ops after legalize
Stephen Hinesdce4a402014-05-29 02:49:00 -07001999 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2000 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman405e3ec2005-10-21 00:02:42 +00002001 // If dividing by powers of two is cheap, then don't perform the following
2002 // fold.
2003 if (TLI.isPow2DivCheap())
Dan Gohman475871a2008-07-27 21:46:04 +00002004 return SDValue();
Bill Wendling944d34b2009-01-30 02:52:17 +00002005
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002006 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling944d34b2009-01-30 02:52:17 +00002007
Chris Lattner8f4880b2006-02-16 08:02:36 +00002008 // Splat the sign bit into the register
Stephen Hinesdce4a402014-05-29 02:49:00 -07002009 SDValue SGN =
2010 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2011 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2012 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00002013 AddToWorkList(SGN.getNode());
Bill Wendling944d34b2009-01-30 02:52:17 +00002014
Chris Lattner8f4880b2006-02-16 08:02:36 +00002015 // Add (N0 < 0) ? abs2 - 1 : 0;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002016 SDValue SRL =
2017 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2018 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2019 getShiftAmountTy(SGN.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +00002020 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002021 AddToWorkList(SRL.getNode());
2022 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickac6d9be2013-05-25 02:42:55 +00002023 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Anderson95771af2011-02-25 21:41:48 +00002024 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling944d34b2009-01-30 02:52:17 +00002025
Nate Begeman405e3ec2005-10-21 00:02:42 +00002026 // If we're dividing by a positive value, we're done. Otherwise, we must
2027 // negate the result.
Eli Friedmanfd58cd72011-10-27 02:06:39 +00002028 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman405e3ec2005-10-21 00:02:42 +00002029 return SRA;
Bill Wendling944d34b2009-01-30 02:52:17 +00002030
Gabor Greifba36cb52008-08-28 21:40:38 +00002031 AddToWorkList(SRA.getNode());
Stephen Hinesdce4a402014-05-29 02:49:00 -07002032 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman405e3ec2005-10-21 00:02:42 +00002033 }
Bill Wendling944d34b2009-01-30 02:52:17 +00002034
Nate Begeman69575232005-10-20 02:15:44 +00002035 // if integer divide is expensive and we satisfy the requirements, emit an
2036 // alternate sequence.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002037 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002038 SDValue Op = BuildSDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002039 if (Op.getNode()) return Op;
Nate Begeman69575232005-10-20 02:15:44 +00002040 }
Dan Gohman7f321562007-06-25 16:23:39 +00002041
Dan Gohman613e0d82007-07-03 14:03:57 +00002042 // undef / X -> 0
2043 if (N0.getOpcode() == ISD::UNDEF)
2044 return DAG.getConstant(0, VT);
2045 // X / undef -> undef
2046 if (N1.getOpcode() == ISD::UNDEF)
2047 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002048
Dan Gohman475871a2008-07-27 21:46:04 +00002049 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002050}
2051
Dan Gohman475871a2008-07-27 21:46:04 +00002052SDValue DAGCombiner::visitUDIV(SDNode *N) {
2053 SDValue N0 = N->getOperand(0);
2054 SDValue N1 = N->getOperand(1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002055 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2056 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002057 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002058
Dan Gohman7f321562007-06-25 16:23:39 +00002059 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002060 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002061 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002062 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002063 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002064
Nate Begeman1d4d4142005-09-01 00:19:25 +00002065 // fold (udiv c1, c2) -> c1/c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002066 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002067 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002068 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman002e5d02008-03-13 22:13:53 +00002069 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002070 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002071 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Anderson95771af2011-02-25 21:41:48 +00002072 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002073 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002074 if (N1.getOpcode() == ISD::SHL) {
2075 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002076 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Andersone50ed302009-08-10 22:56:29 +00002077 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002078 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendling07d85142009-01-30 02:55:25 +00002079 N1.getOperand(1),
2080 DAG.getConstant(SHC->getAPIntValue()
2081 .logBase2(),
2082 ADDVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002083 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002084 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begemanfb5e4bd2006-02-05 07:20:23 +00002085 }
2086 }
2087 }
Nate Begeman69575232005-10-20 02:15:44 +00002088 // fold (udiv x, c) -> alternate
Stephen Hinesdce4a402014-05-29 02:49:00 -07002089 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002090 SDValue Op = BuildUDIV(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002091 if (Op.getNode()) return Op;
Chris Lattnere9936d12005-10-22 18:50:15 +00002092 }
Dan Gohman7f321562007-06-25 16:23:39 +00002093
Dan Gohman613e0d82007-07-03 14:03:57 +00002094 // undef / X -> 0
2095 if (N0.getOpcode() == ISD::UNDEF)
2096 return DAG.getConstant(0, VT);
2097 // X / undef -> undef
2098 if (N1.getOpcode() == ISD::UNDEF)
2099 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002100
Dan Gohman475871a2008-07-27 21:46:04 +00002101 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002102}
2103
Dan Gohman475871a2008-07-27 21:46:04 +00002104SDValue DAGCombiner::visitSREM(SDNode *N) {
2105 SDValue N0 = N->getOperand(0);
2106 SDValue N1 = N->getOperand(1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002107 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2108 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002109 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002110
Nate Begeman1d4d4142005-09-01 00:19:25 +00002111 // fold (srem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002112 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002113 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002114 // If we know the sign bits of both operands are zero, strength reduce to a
2115 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands83ec4b62008-06-06 12:08:01 +00002116 if (!VT.isVector()) {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002118 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattneree339f42008-01-27 23:21:58 +00002119 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002120
Dan Gohman77003042007-11-26 23:46:11 +00002121 // If X/C can be simplified by the division-by-constant logic, lower
2122 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002123 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002124 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00002125 AddToWorkList(Div.getNode());
2126 SDValue OptimizedDiv = combine(Div.getNode());
2127 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002128 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002129 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002130 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002131 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002132 return Sub;
2133 }
Chris Lattner26d29902006-10-12 20:58:32 +00002134 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002135
Dan Gohman613e0d82007-07-03 14:03:57 +00002136 // undef % X -> 0
2137 if (N0.getOpcode() == ISD::UNDEF)
2138 return DAG.getConstant(0, VT);
2139 // X % undef -> undef
2140 if (N1.getOpcode() == ISD::UNDEF)
2141 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002142
Dan Gohman475871a2008-07-27 21:46:04 +00002143 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002144}
2145
Dan Gohman475871a2008-07-27 21:46:04 +00002146SDValue DAGCombiner::visitUREM(SDNode *N) {
2147 SDValue N0 = N->getOperand(0);
2148 SDValue N1 = N->getOperand(1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002149 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2150 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002151 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002152
Nate Begeman1d4d4142005-09-01 00:19:25 +00002153 // fold (urem c1, c2) -> c1%c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002154 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002155 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman07ed4172005-10-10 21:26:48 +00002156 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002157 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohman002e5d02008-03-13 22:13:53 +00002159 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc031e332006-02-05 07:36:48 +00002160 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2161 if (N1.getOpcode() == ISD::SHL) {
2162 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman002e5d02008-03-13 22:13:53 +00002163 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002164 SDValue Add =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002165 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands83ec4b62008-06-06 12:08:01 +00002166 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohman002e5d02008-03-13 22:13:53 +00002167 VT));
Gabor Greifba36cb52008-08-28 21:40:38 +00002168 AddToWorkList(Add.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc031e332006-02-05 07:36:48 +00002170 }
2171 }
2172 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002173
Dan Gohman77003042007-11-26 23:46:11 +00002174 // If X/C can be simplified by the division-by-constant logic, lower
2175 // X%C to the equivalent of X-X/C*C.
Chris Lattner26d29902006-10-12 20:58:32 +00002176 if (N1C && !N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002177 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman942ca7f2008-09-08 16:59:01 +00002178 AddToWorkList(Div.getNode());
Gabor Greifba36cb52008-08-28 21:40:38 +00002179 SDValue OptimizedDiv = combine(Div.getNode());
2180 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002181 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling6d3bf8c2009-01-30 02:57:00 +00002182 OptimizedDiv, N1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002183 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greifba36cb52008-08-28 21:40:38 +00002184 AddToWorkList(Mul.getNode());
Dan Gohman77003042007-11-26 23:46:11 +00002185 return Sub;
2186 }
Chris Lattner26d29902006-10-12 20:58:32 +00002187 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002188
Dan Gohman613e0d82007-07-03 14:03:57 +00002189 // undef % X -> 0
2190 if (N0.getOpcode() == ISD::UNDEF)
2191 return DAG.getConstant(0, VT);
2192 // X % undef -> undef
2193 if (N1.getOpcode() == ISD::UNDEF)
2194 return N1;
Dan Gohman7f321562007-06-25 16:23:39 +00002195
Dan Gohman475871a2008-07-27 21:46:04 +00002196 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002197}
2198
Dan Gohman475871a2008-07-27 21:46:04 +00002199SDValue DAGCombiner::visitMULHS(SDNode *N) {
2200 SDValue N0 = N->getOperand(0);
2201 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002203 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002204 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002205
Nate Begeman1d4d4142005-09-01 00:19:25 +00002206 // fold (mulhs x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002207 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002208 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002209 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman002e5d02008-03-13 22:13:53 +00002210 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002211 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendling326411d2009-01-30 03:00:18 +00002212 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Anderson95771af2011-02-25 21:41:48 +00002213 getShiftAmountTy(N0.getValueType())));
Dan Gohman613e0d82007-07-03 14:03:57 +00002214 // fold (mulhs x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002215 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002216 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002217
Chris Lattnerde1c3602010-12-13 08:39:01 +00002218 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2219 // plus a shift.
2220 if (VT.isSimple() && !VT.isVector()) {
2221 MVT Simple = VT.getSimpleVT();
2222 unsigned SimpleSize = Simple.getSizeInBits();
2223 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2226 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2227 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattner1a0fbe22010-12-15 05:51:39 +00002228 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002229 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002230 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2231 }
2232 }
Owen Anderson95771af2011-02-25 21:41:48 +00002233
Dan Gohman475871a2008-07-27 21:46:04 +00002234 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002235}
2236
Dan Gohman475871a2008-07-27 21:46:04 +00002237SDValue DAGCombiner::visitMULHU(SDNode *N) {
2238 SDValue N0 = N->getOperand(0);
2239 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00002240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002241 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002242 SDLoc DL(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00002243
Nate Begeman1d4d4142005-09-01 00:19:25 +00002244 // fold (mulhu x, 0) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00002245 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002246 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00002247 // fold (mulhu x, 1) -> 0
Dan Gohman002e5d02008-03-13 22:13:53 +00002248 if (N1C && N1C->getAPIntValue() == 1)
Nate Begeman83e75ec2005-09-06 04:43:02 +00002249 return DAG.getConstant(0, N0.getValueType());
Dan Gohman613e0d82007-07-03 14:03:57 +00002250 // fold (mulhu x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002251 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002252 return DAG.getConstant(0, VT);
Dan Gohman7f321562007-06-25 16:23:39 +00002253
Chris Lattnerde1c3602010-12-13 08:39:01 +00002254 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2255 // plus a shift.
2256 if (VT.isSimple() && !VT.isVector()) {
2257 MVT Simple = VT.getSimpleVT();
2258 unsigned SimpleSize = Simple.getSizeInBits();
2259 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2260 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2261 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2262 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2263 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2264 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Anderson95771af2011-02-25 21:41:48 +00002265 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattnerde1c3602010-12-13 08:39:01 +00002266 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2267 }
2268 }
Owen Anderson95771af2011-02-25 21:41:48 +00002269
Dan Gohman475871a2008-07-27 21:46:04 +00002270 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002271}
2272
Dan Gohman389079b2007-10-08 17:57:15 +00002273/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2274/// compute two values. LoOp and HiOp give the opcodes for the two computations
2275/// that are being performed. Return true if a simplification was made.
2276///
Scott Michelfdc40a02009-02-17 22:15:04 +00002277SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman475871a2008-07-27 21:46:04 +00002278 unsigned HiOp) {
Dan Gohman389079b2007-10-08 17:57:15 +00002279 // If the high half is not needed, just compute the low half.
Evan Cheng44711942007-11-08 09:25:29 +00002280 bool HiExists = N->hasAnyUseOfValue(1);
2281 if (!HiExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002282 (!LegalOperations ||
Stephen Hines36b56882014-04-23 16:57:46 -07002283 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002284 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Stephen Hinesdce4a402014-05-29 02:49:00 -07002285 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner5eee4272008-01-26 01:09:19 +00002286 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002287 }
2288
2289 // If the low half is not needed, just compute the high half.
Evan Cheng44711942007-11-08 09:25:29 +00002290 bool LoExists = N->hasAnyUseOfValue(0);
2291 if (!LoExists &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002292 (!LegalOperations ||
Dan Gohman389079b2007-10-08 17:57:15 +00002293 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002294 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Stephen Hinesdce4a402014-05-29 02:49:00 -07002295 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner5eee4272008-01-26 01:09:19 +00002296 return CombineTo(N, Res, Res);
Dan Gohman389079b2007-10-08 17:57:15 +00002297 }
2298
Evan Cheng44711942007-11-08 09:25:29 +00002299 // If both halves are used, return as it is.
2300 if (LoExists && HiExists)
Dan Gohman475871a2008-07-27 21:46:04 +00002301 return SDValue();
Evan Cheng44711942007-11-08 09:25:29 +00002302
2303 // If the two computed results can be simplified separately, separate them.
Evan Cheng44711942007-11-08 09:25:29 +00002304 if (LoExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002305 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Stephen Hinesdce4a402014-05-29 02:49:00 -07002306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greifba36cb52008-08-28 21:40:38 +00002307 AddToWorkList(Lo.getNode());
2308 SDValue LoOpt = combine(Lo.getNode());
2309 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002310 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002311 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002312 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman389079b2007-10-08 17:57:15 +00002313 }
2314
Evan Cheng44711942007-11-08 09:25:29 +00002315 if (HiExists) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002316 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Stephen Hinesdce4a402014-05-29 02:49:00 -07002317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greifba36cb52008-08-28 21:40:38 +00002318 AddToWorkList(Hi.getNode());
2319 SDValue HiOpt = combine(Hi.getNode());
2320 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002321 (!LegalOperations ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +00002322 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner5eee4272008-01-26 01:09:19 +00002323 return CombineTo(N, HiOpt, HiOpt);
Evan Cheng44711942007-11-08 09:25:29 +00002324 }
Bill Wendling826d1142009-01-30 03:08:40 +00002325
Dan Gohman475871a2008-07-27 21:46:04 +00002326 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002327}
2328
Dan Gohman475871a2008-07-27 21:46:04 +00002329SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2330 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greifba36cb52008-08-28 21:40:38 +00002331 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002332
Chris Lattner33e77d32010-12-15 06:04:19 +00002333 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002334 SDLoc DL(N);
Chris Lattner33e77d32010-12-15 06:04:19 +00002335
2336 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337 // plus a shift.
2338 if (VT.isSimple() && !VT.isVector()) {
2339 MVT Simple = VT.getSimpleVT();
2340 unsigned SimpleSize = Simple.getSizeInBits();
2341 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2344 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2345 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2346 // Compute the high part as N1.
2347 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002348 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002349 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2350 // Compute the low part as N0.
2351 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2352 return CombineTo(N, Lo, Hi);
2353 }
2354 }
Owen Anderson95771af2011-02-25 21:41:48 +00002355
Dan Gohman475871a2008-07-27 21:46:04 +00002356 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002357}
2358
Dan Gohman475871a2008-07-27 21:46:04 +00002359SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2360 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greifba36cb52008-08-28 21:40:38 +00002361 if (Res.getNode()) return Res;
Dan Gohman389079b2007-10-08 17:57:15 +00002362
Chris Lattner33e77d32010-12-15 06:04:19 +00002363 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00002364 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00002365
Chris Lattner33e77d32010-12-15 06:04:19 +00002366 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2367 // plus a shift.
2368 if (VT.isSimple() && !VT.isVector()) {
2369 MVT Simple = VT.getSimpleVT();
2370 unsigned SimpleSize = Simple.getSizeInBits();
2371 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2372 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2373 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2374 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2375 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2376 // Compute the high part as N1.
2377 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Anderson95771af2011-02-25 21:41:48 +00002378 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner33e77d32010-12-15 06:04:19 +00002379 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2380 // Compute the low part as N0.
2381 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2382 return CombineTo(N, Lo, Hi);
2383 }
2384 }
Owen Anderson95771af2011-02-25 21:41:48 +00002385
Dan Gohman475871a2008-07-27 21:46:04 +00002386 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002387}
2388
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002389SDValue DAGCombiner::visitSMULO(SDNode *N) {
2390 // (smulo x, 2) -> (saddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002393 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002394 N->getOperand(0), N->getOperand(0));
2395
2396 return SDValue();
2397}
2398
2399SDValue DAGCombiner::visitUMULO(SDNode *N) {
2400 // (umulo x, 2) -> (uaddo x, x)
2401 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2402 if (C2->getAPIntValue() == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002403 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramerf55d26e2011-05-21 18:31:55 +00002404 N->getOperand(0), N->getOperand(0));
2405
2406 return SDValue();
2407}
2408
Dan Gohman475871a2008-07-27 21:46:04 +00002409SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002411 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002412
Dan Gohman475871a2008-07-27 21:46:04 +00002413 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002414}
2415
Dan Gohman475871a2008-07-27 21:46:04 +00002416SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2417 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greifba36cb52008-08-28 21:40:38 +00002418 if (Res.getNode()) return Res;
Scott Michelfdc40a02009-02-17 22:15:04 +00002419
Dan Gohman475871a2008-07-27 21:46:04 +00002420 return SDValue();
Dan Gohman389079b2007-10-08 17:57:15 +00002421}
2422
Chris Lattner35e5c142006-05-05 05:51:50 +00002423/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2424/// two operands of the same opcode, try to simplify it.
Dan Gohman475871a2008-07-27 21:46:04 +00002425SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2426 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00002427 EVT VT = N0.getValueType();
Chris Lattner35e5c142006-05-05 05:51:50 +00002428 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelfdc40a02009-02-17 22:15:04 +00002429
Dan Gohmanff00a552010-01-14 03:08:49 +00002430 // Bail early if none of these transforms apply.
2431 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2432
Chris Lattner540121f2006-05-05 06:31:05 +00002433 // For each of OP in AND/OR/XOR:
2434 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2435 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2436 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002437 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman93e0ed32009-12-03 07:11:29 +00002438 //
2439 // do not sink logical op inside of a vector extend, since it may combine
2440 // into a vsetcc.
Evan Chengd40d03e2010-01-06 19:38:29 +00002441 EVT Op0VT = N0.getOperand(0).getValueType();
2442 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohman97121ba2009-04-08 00:15:30 +00002443 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chenge5b51ac2010-04-17 06:13:15 +00002444 // Avoid infinite looping with PromoteIntBinOp.
2445 (N0.getOpcode() == ISD::ANY_EXTEND &&
2446 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman4e39e9d2010-06-24 14:30:44 +00002447 (N0.getOpcode() == ISD::TRUNCATE &&
2448 (!TLI.isZExtFree(VT, Op0VT) ||
2449 !TLI.isTruncateFree(Op0VT, VT)) &&
2450 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman93e0ed32009-12-03 07:11:29 +00002451 !VT.isVector() &&
Evan Chengd40d03e2010-01-06 19:38:29 +00002452 Op0VT == N1.getOperand(0).getValueType() &&
2453 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002454 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002455 N0.getOperand(0).getValueType(),
2456 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002457 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002458 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner35e5c142006-05-05 05:51:50 +00002459 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002460
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002461 // For each of OP in SHL/SRL/SRA/AND...
2462 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2463 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2464 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner35e5c142006-05-05 05:51:50 +00002465 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattnera3dc3f62006-05-05 06:10:43 +00002466 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner35e5c142006-05-05 05:51:50 +00002467 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002468 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendlingb74c8672009-01-30 19:25:47 +00002469 N0.getOperand(0).getValueType(),
2470 N0.getOperand(0), N1.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00002471 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002472 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendlingb74c8672009-01-30 19:25:47 +00002473 ORNode, N0.getOperand(1));
Chris Lattner35e5c142006-05-05 05:51:50 +00002474 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002475
Nadav Rotem4ac90812012-04-01 19:31:22 +00002476 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2477 // Only perform this optimization after type legalization and before
2478 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2479 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2480 // we don't want to undo this promotion.
2481 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2482 // on scalars.
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002483 if ((N0.getOpcode() == ISD::BITCAST ||
2484 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2485 Level == AfterLegalizeTypes) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002486 SDValue In0 = N0.getOperand(0);
2487 SDValue In1 = N1.getOperand(0);
2488 EVT In0Ty = In0.getValueType();
2489 EVT In1Ty = In1.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002490 SDLoc DL(N);
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002491 // If both incoming values are integers, and the original types are the
2492 // same.
Nadav Rotem4ac90812012-04-01 19:31:22 +00002493 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem6dfabb62012-09-20 08:53:31 +00002494 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2495 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002496 AddToWorkList(Op.getNode());
2497 return BC;
2498 }
2499 }
2500
2501 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2502 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2503 // If both shuffles use the same mask, and both shuffle within a single
2504 // vector, then it is worthwhile to move the swizzle after the operation.
2505 // The type-legalizer generates this pattern when loading illegal
2506 // vector types from memory. In many cases this allows additional shuffle
2507 // optimizations.
Stephen Hines36b56882014-04-23 16:57:46 -07002508 // There are other cases where moving the shuffle after the xor/and/or
2509 // is profitable even if shuffles don't perform a swizzle.
2510 // If both shuffles use the same mask, and both shuffles have the same first
2511 // or second operand, then it might still be profitable to move the shuffle
2512 // after the xor/and/or operation.
2513 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotem4ac90812012-04-01 19:31:22 +00002514 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2515 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topperf9204232012-04-09 07:19:09 +00002516
Stephen Hines36b56882014-04-23 16:57:46 -07002517 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topperf9204232012-04-09 07:19:09 +00002518 "Inputs to shuffles are not the same type");
Stephen Hinesdce4a402014-05-29 02:49:00 -07002519
Nadav Rotem4ac90812012-04-01 19:31:22 +00002520 // Check that both shuffles use the same mask. The masks are known to be of
2521 // the same length because the result vector type is the same.
Stephen Hines36b56882014-04-23 16:57:46 -07002522 // Check also that shuffles have only one use to avoid introducing extra
2523 // instructions.
2524 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2525 SVN0->getMask().equals(SVN1->getMask())) {
2526 SDValue ShOp = N0->getOperand(1);
Nadav Rotem4ac90812012-04-01 19:31:22 +00002527
Stephen Hines36b56882014-04-23 16:57:46 -07002528 // Don't try to fold this node if it requires introducing a
2529 // build vector of all zeros that might be illegal at this stage.
2530 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2531 if (!LegalTypes)
2532 ShOp = DAG.getConstant(0, VT);
2533 else
2534 ShOp = SDValue();
2535 }
2536
2537 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2538 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2539 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2540 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2541 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2542 N0->getOperand(0), N1->getOperand(0));
2543 AddToWorkList(NewNode.getNode());
2544 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2545 &SVN0->getMask()[0]);
2546 }
2547
2548 // Don't try to fold this node if it requires introducing a
2549 // build vector of all zeros that might be illegal at this stage.
2550 ShOp = N0->getOperand(0);
2551 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2552 if (!LegalTypes)
2553 ShOp = DAG.getConstant(0, VT);
2554 else
2555 ShOp = SDValue();
2556 }
2557
2558 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2559 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2560 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2561 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2562 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2563 N0->getOperand(1), N1->getOperand(1));
2564 AddToWorkList(NewNode.getNode());
2565 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2566 &SVN0->getMask()[0]);
2567 }
Nadav Rotem4ac90812012-04-01 19:31:22 +00002568 }
2569 }
Craig Topperf9204232012-04-09 07:19:09 +00002570
Dan Gohman475871a2008-07-27 21:46:04 +00002571 return SDValue();
Chris Lattner35e5c142006-05-05 05:51:50 +00002572}
2573
Dan Gohman475871a2008-07-27 21:46:04 +00002574SDValue DAGCombiner::visitAND(SDNode *N) {
2575 SDValue N0 = N->getOperand(0);
2576 SDValue N1 = N->getOperand(1);
2577 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00002578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00002580 EVT VT = N1.getValueType();
Dan Gohman6900a392010-03-04 00:23:16 +00002581 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00002582
Dan Gohman7f321562007-06-25 16:23:39 +00002583 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00002584 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002585 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002586 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00002587
2588 // fold (and x, 0) -> 0, vector edition
2589 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2590 return N0;
2591 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2592 return N1;
2593
2594 // fold (and x, -1) -> x, vector edition
2595 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2596 return N1;
2597 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2598 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00002599 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002600
Dan Gohman613e0d82007-07-03 14:03:57 +00002601 // fold (and x, undef) -> 0
Dan Gohmand595b5f2007-07-10 14:20:37 +00002602 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00002603 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002604 // fold (and c1, c2) -> c1&c2
Nate Begeman646d7e22005-09-02 21:18:40 +00002605 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00002606 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00002607 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00002608 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002609 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00002610 // fold (and x, -1) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00002611 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002612 return N0;
2613 // if (and x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00002614 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002615 APInt::getAllOnesValue(BitWidth)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00002616 return DAG.getConstant(0, VT);
Nate Begemancd4d58c2006-02-03 06:46:56 +00002617 // reassociate and
Andrew Trickac6d9be2013-05-25 02:42:55 +00002618 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07002619 if (RAND.getNode())
Nate Begemancd4d58c2006-02-03 06:46:56 +00002620 return RAND;
Bill Wendling7d9f2b92010-03-03 00:35:56 +00002621 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begeman5dc7e862005-11-02 18:42:59 +00002622 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman1d4d4142005-09-01 00:19:25 +00002623 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman002e5d02008-03-13 22:13:53 +00002624 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00002625 return N1;
Chris Lattner3603cd62006-02-02 07:17:31 +00002626 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2627 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman475871a2008-07-27 21:46:04 +00002628 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002629 APInt Mask = ~N1C->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00002630 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002631 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002632 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling2627a882009-01-30 20:43:18 +00002633 N0.getValueType(), N0Op0);
Scott Michelfdc40a02009-02-17 22:15:04 +00002634
Chris Lattner1ec05d12006-03-01 21:47:21 +00002635 // Replace uses of the AND with uses of the Zero extend node.
2636 CombineTo(N, Zext);
Scott Michelfdc40a02009-02-17 22:15:04 +00002637
Chris Lattner3603cd62006-02-02 07:17:31 +00002638 // We actually want to replace all uses of the any_extend with the
2639 // zero_extend, to avoid duplicating things. This will later cause this
2640 // AND to be folded.
Gabor Greifba36cb52008-08-28 21:40:38 +00002641 CombineTo(N0.getNode(), Zext);
Dan Gohman475871a2008-07-27 21:46:04 +00002642 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3603cd62006-02-02 07:17:31 +00002643 }
2644 }
Stephen Lin155615d2013-07-08 00:37:03 +00002645 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy6259dcd2012-02-20 12:02:38 +00002646 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2647 // already be zero by virtue of the width of the base type of the load.
2648 //
2649 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2650 // more cases.
2651 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2652 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2653 N0.getOpcode() == ISD::LOAD) {
2654 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2655 N0 : N0.getOperand(0) );
2656
2657 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2658 // This can be a pure constant or a vector splat, in which case we treat the
2659 // vector as a scalar and use the splat value.
2660 APInt Constant = APInt::getNullValue(1);
2661 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2662 Constant = C->getAPIntValue();
2663 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2664 APInt SplatValue, SplatUndef;
2665 unsigned SplatBitSize;
2666 bool HasAnyUndefs;
2667 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2668 SplatBitSize, HasAnyUndefs);
2669 if (IsSplat) {
2670 // Undef bits can contribute to a possible optimisation if set, so
2671 // set them.
2672 SplatValue |= SplatUndef;
2673
2674 // The splat value may be something like "0x00FFFFFF", which means 0 for
2675 // the first vector value and FF for the rest, repeating. We need a mask
2676 // that will apply equally to all members of the vector, so AND all the
2677 // lanes of the constant together.
2678 EVT VT = Vector->getValueType(0);
2679 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002680
2681 // If the splat value has been compressed to a bitlength lower
2682 // than the size of the vector lane, we need to re-expand it to
2683 // the lane size.
2684 if (BitWidth > SplatBitSize)
2685 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2686 SplatBitSize < BitWidth;
2687 SplatBitSize = SplatBitSize * 2)
2688 SplatValue |= SplatValue.shl(SplatBitSize);
2689
James Molloy6259dcd2012-02-20 12:02:38 +00002690 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3d5e1612012-09-05 08:57:21 +00002691 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy6259dcd2012-02-20 12:02:38 +00002692 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2693 }
2694 }
2695
2696 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2697 // actually legal and isn't going to get expanded, else this is a false
2698 // optimisation.
2699 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2700 Load->getMemoryVT());
2701
2702 // Resize the constant to the same size as the original memory access before
2703 // extension. If it is still the AllOnesValue then this AND is completely
2704 // unneeded.
2705 Constant =
2706 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2707
2708 bool B;
2709 switch (Load->getExtensionType()) {
2710 default: B = false; break;
2711 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2712 case ISD::ZEXTLOAD:
2713 case ISD::NON_EXTLOAD: B = true; break;
2714 }
2715
2716 if (B && Constant.isAllOnesValue()) {
2717 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2718 // preserve semantics once we get rid of the AND.
2719 SDValue NewLoad(Load, 0);
2720 if (Load->getExtensionType() == ISD::EXTLOAD) {
2721 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickac6d9be2013-05-25 02:42:55 +00002722 Load->getValueType(0), SDLoc(Load),
James Molloy6259dcd2012-02-20 12:02:38 +00002723 Load->getChain(), Load->getBasePtr(),
2724 Load->getOffset(), Load->getMemoryVT(),
2725 Load->getMemOperand());
2726 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkeld65e4632012-06-20 15:42:48 +00002727 if (Load->getNumValues() == 3) {
2728 // PRE/POST_INC loads have 3 values.
2729 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2730 NewLoad.getValue(2) };
2731 CombineTo(Load, To, 3, true);
2732 } else {
2733 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2734 }
James Molloy6259dcd2012-02-20 12:02:38 +00002735 }
2736
2737 // Fold the AND away, taking care not to fold to the old load node if we
2738 // replaced it.
2739 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2740
2741 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2742 }
2743 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002744 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2745 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2746 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2747 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00002748
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002749 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00002750 LL.getValueType().isInteger()) {
Bill Wendling2627a882009-01-30 20:43:18 +00002751 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohman002e5d02008-03-13 22:13:53 +00002752 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002753 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002754 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002755 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002756 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002757 }
Bill Wendling2627a882009-01-30 20:43:18 +00002758 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002759 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002760 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002761 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002762 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002763 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002764 }
Bill Wendling2627a882009-01-30 20:43:18 +00002765 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002766 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002767 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling2627a882009-01-30 20:43:18 +00002768 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00002769 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002770 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002771 }
2772 }
Jim Grosbach51a02802013-08-13 21:30:58 +00002773 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2774 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2775 Op0 == Op1 && LL.getValueType().isInteger() &&
2776 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2777 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2778 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2779 cast<ConstantSDNode>(RR)->isNullValue()))) {
2780 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2781 LL, DAG.getConstant(1, LL.getValueType()));
2782 AddToWorkList(ADDNode.getNode());
2783 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2784 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2785 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002786 // canonicalize equivalent to ll == rl
2787 if (LL == RR && LR == RL) {
2788 Op1 = ISD::getSetCCSwappedOperands(Op1);
2789 std::swap(RL, RR);
2790 }
2791 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002792 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002793 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00002794 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00002795 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00002796 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00002798 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00002799 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling2627a882009-01-30 20:43:18 +00002800 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002801 }
2802 }
Chris Lattner35e5c142006-05-05 05:51:50 +00002803
Bill Wendling2627a882009-01-30 20:43:18 +00002804 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00002805 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00002806 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002807 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00002808 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002809
Nate Begemande996292006-02-03 22:24:05 +00002810 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2811 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands83ec4b62008-06-06 12:08:01 +00002812 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00002813 SimplifyDemandedBits(SDValue(N, 0)))
2814 return SDValue(N, 0);
Evan Chengd40d03e2010-01-06 19:38:29 +00002815
Nate Begemanded49632005-10-13 03:11:28 +00002816 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greifba36cb52008-08-28 21:40:38 +00002817 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Cheng466685d2006-10-09 20:57:25 +00002818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002819 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002820 // If we zero all the possible extended bits, then we can turn this into
2821 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002822 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002823 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002824 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002825 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002826 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002827 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling2627a882009-01-30 20:43:18 +00002828 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002829 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002830 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002831 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002833 }
2834 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002835 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00002836 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00002837 N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00002838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00002839 EVT MemVT = LN0->getMemoryVT();
Nate Begemanbfd65a02005-10-13 18:34:58 +00002840 // If we zero all the possible extended bits, then we can turn this into
2841 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman6900a392010-03-04 00:23:16 +00002842 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman2e68b6f2008-02-25 21:11:39 +00002843 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohman6900a392010-03-04 00:23:16 +00002844 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00002845 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00002846 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00002847 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002848 LN0->getChain(), LN0->getBasePtr(),
2849 MemVT, LN0->getMemOperand());
Chris Lattner5750df92006-03-01 04:03:14 +00002850 AddToWorkList(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00002851 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00002852 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00002853 }
2854 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002855
Chris Lattner35a9f5a2006-02-28 06:49:37 +00002856 // fold (and (load x), 255) -> (zextload x, i8)
2857 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Chengd40d03e2010-01-06 19:38:29 +00002858 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2859 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2860 (N0.getOpcode() == ISD::ANY_EXTEND &&
2861 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2862 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2863 LoadSDNode *LN0 = HasAnyExt
2864 ? cast<LoadSDNode>(N0.getOperand(0))
2865 : cast<LoadSDNode>(N0);
Evan Cheng466685d2006-10-09 20:57:25 +00002866 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover5bce67a2013-07-02 09:58:53 +00002867 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands8eab8a22008-06-09 11:32:28 +00002868 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Chengd40d03e2010-01-06 19:38:29 +00002869 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2870 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2871 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands8eab8a22008-06-09 11:32:28 +00002872
Evan Chengd40d03e2010-01-06 19:38:29 +00002873 if (ExtVT == LoadedVT &&
2874 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattneref7634c2010-01-07 21:53:27 +00002875 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002876
2877 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002878 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford66589dc2013-10-28 11:17:59 +00002879 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2880 LN0->getMemOperand());
Chris Lattneref7634c2010-01-07 21:53:27 +00002881 AddToWorkList(N);
2882 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2883 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2884 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002885
Chris Lattneref7634c2010-01-07 21:53:27 +00002886 // Do not change the width of a volatile load.
2887 // Do not generate loads of non-round integer types since these can
2888 // be expensive (and would be wrong if the type is not byte sized).
2889 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling2627a882009-01-30 20:43:18 +00002892
Chris Lattneref7634c2010-01-07 21:53:27 +00002893 unsigned Alignment = LN0->getAlignment();
2894 SDValue NewPtr = LN0->getBasePtr();
2895
2896 // For big endian targets, we need to add an offset to the pointer
2897 // to load the correct bytes. For little endian systems, we merely
2898 // need to read fewer bytes from the same pointer.
2899 if (TLI.isBigEndian()) {
Evan Chengd40d03e2010-01-06 19:38:29 +00002900 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2901 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2902 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickac6d9be2013-05-25 02:42:55 +00002903 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattneref7634c2010-01-07 21:53:27 +00002904 NewPtr, DAG.getConstant(PtrOff, PtrType));
2905 Alignment = MinAlign(Alignment, PtrOff);
Evan Chengd40d03e2010-01-06 19:38:29 +00002906 }
Chris Lattneref7634c2010-01-07 21:53:27 +00002907
2908 AddToWorkList(NewPtr.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002909
Chris Lattneref7634c2010-01-07 21:53:27 +00002910 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2911 SDValue Load =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002912 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattneref7634c2010-01-07 21:53:27 +00002913 LN0->getChain(), NewPtr,
Chris Lattner3d6ccfb2010-09-21 17:04:51 +00002914 LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00002915 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00002916 Alignment, LN0->getTBAAInfo());
Chris Lattneref7634c2010-01-07 21:53:27 +00002917 AddToWorkList(N);
2918 CombineTo(LN0, Load, Load.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsdc846502007-10-28 12:59:45 +00002920 }
Evan Cheng466685d2006-10-09 20:57:25 +00002921 }
Chris Lattner15045b62006-02-28 06:35:35 +00002922 }
2923 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002924
Evan Chenga9e13ba2012-07-17 18:54:11 +00002925 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2926 VT.getSizeInBits() <= 64) {
2927 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2928 APInt ADDC = ADDI->getAPIntValue();
2929 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2931 // immediate for an add, but it is legal if its top c2 bits are set,
2932 // transform the ADD so the immediate doesn't need to be materialized
2933 // in a register.
2934 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2935 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2936 SRLI->getZExtValue());
2937 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2938 ADDC |= Mask;
2939 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2940 SDValue NewAdd =
Andrew Trickac6d9be2013-05-25 02:42:55 +00002941 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenga9e13ba2012-07-17 18:54:11 +00002942 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2943 CombineTo(N0.getNode(), NewAdd);
2944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2945 }
2946 }
2947 }
2948 }
2949 }
2950 }
Evan Chenga9e13ba2012-07-17 18:54:11 +00002951
Tim Northover5d8c2e42013-08-27 13:46:45 +00002952 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2953 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2954 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2955 N0.getOperand(1), false);
2956 if (BSwap.getNode())
2957 return BSwap;
2958 }
2959
Evan Chengb3a3d5e2010-04-28 07:10:39 +00002960 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00002961}
2962
Evan Cheng9568e5c2011-06-21 06:01:08 +00002963/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2964///
2965SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2966 bool DemandHighBits) {
2967 if (!LegalOperations)
2968 return SDValue();
2969
2970 EVT VT = N->getValueType(0);
2971 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2972 return SDValue();
2973 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2974 return SDValue();
2975
2976 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2977 bool LookPassAnd0 = false;
2978 bool LookPassAnd1 = false;
2979 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2980 std::swap(N0, N1);
2981 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2982 std::swap(N0, N1);
2983 if (N0.getOpcode() == ISD::AND) {
2984 if (!N0.getNode()->hasOneUse())
2985 return SDValue();
2986 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2987 if (!N01C || N01C->getZExtValue() != 0xFF00)
2988 return SDValue();
2989 N0 = N0.getOperand(0);
2990 LookPassAnd0 = true;
2991 }
2992
2993 if (N1.getOpcode() == ISD::AND) {
2994 if (!N1.getNode()->hasOneUse())
2995 return SDValue();
2996 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2997 if (!N11C || N11C->getZExtValue() != 0xFF)
2998 return SDValue();
2999 N1 = N1.getOperand(0);
3000 LookPassAnd1 = true;
3001 }
3002
3003 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3004 std::swap(N0, N1);
3005 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3006 return SDValue();
3007 if (!N0.getNode()->hasOneUse() ||
3008 !N1.getNode()->hasOneUse())
3009 return SDValue();
3010
3011 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013 if (!N01C || !N11C)
3014 return SDValue();
3015 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3016 return SDValue();
3017
3018 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3019 SDValue N00 = N0->getOperand(0);
3020 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3021 if (!N00.getNode()->hasOneUse())
3022 return SDValue();
3023 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3024 if (!N001C || N001C->getZExtValue() != 0xFF)
3025 return SDValue();
3026 N00 = N00.getOperand(0);
3027 LookPassAnd0 = true;
3028 }
3029
3030 SDValue N10 = N1->getOperand(0);
3031 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3032 if (!N10.getNode()->hasOneUse())
3033 return SDValue();
3034 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3035 if (!N101C || N101C->getZExtValue() != 0xFF00)
3036 return SDValue();
3037 N10 = N10.getOperand(0);
3038 LookPassAnd1 = true;
3039 }
3040
3041 if (N00 != N10)
3042 return SDValue();
3043
Tim Northover5d8c2e42013-08-27 13:46:45 +00003044 // Make sure everything beyond the low halfword gets set to zero since the SRL
3045 // 16 will clear the top bits.
Evan Cheng9568e5c2011-06-21 06:01:08 +00003046 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover5d8c2e42013-08-27 13:46:45 +00003047 if (DemandHighBits && OpSizeInBits > 16) {
3048 // If the left-shift isn't masked out then the only way this is a bswap is
3049 // if all bits beyond the low 8 are 0. In that case the entire pattern
3050 // reduces to a left shift anyway: leave it for other parts of the combiner.
3051 if (!LookPassAnd0)
3052 return SDValue();
3053
3054 // However, if the right shift isn't masked out then it might be because
3055 // it's not needed. See if we can spot that too.
3056 if (!LookPassAnd1 &&
3057 !DAG.MaskedValueIsZero(
3058 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3059 return SDValue();
3060 }
Eric Christopher7332e6e2011-07-14 01:12:15 +00003061
Andrew Trickac6d9be2013-05-25 02:42:55 +00003062 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng9568e5c2011-06-21 06:01:08 +00003063 if (OpSizeInBits > 16)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003064 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng9568e5c2011-06-21 06:01:08 +00003065 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3066 return Res;
3067}
3068
3069/// isBSwapHWordElement - Return true if the specified node is an element
3070/// that makes up a 32-bit packed halfword byteswap. i.e.
3071/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Toppera0ec3f92013-07-14 04:42:23 +00003072static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003073 if (!N.getNode()->hasOneUse())
3074 return false;
3075
3076 unsigned Opc = N.getOpcode();
3077 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3078 return false;
3079
3080 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3081 if (!N1C)
3082 return false;
3083
3084 unsigned Num;
3085 switch (N1C->getZExtValue()) {
3086 default:
3087 return false;
3088 case 0xFF: Num = 0; break;
3089 case 0xFF00: Num = 1; break;
3090 case 0xFF0000: Num = 2; break;
3091 case 0xFF000000: Num = 3; break;
3092 }
3093
3094 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3095 SDValue N0 = N.getOperand(0);
3096 if (Opc == ISD::AND) {
3097 if (Num == 0 || Num == 2) {
3098 // (x >> 8) & 0xff
3099 // (x >> 8) & 0xff0000
3100 if (N0.getOpcode() != ISD::SRL)
3101 return false;
3102 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103 if (!C || C->getZExtValue() != 8)
3104 return false;
3105 } else {
3106 // (x << 8) & 0xff00
3107 // (x << 8) & 0xff000000
3108 if (N0.getOpcode() != ISD::SHL)
3109 return false;
3110 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 if (!C || C->getZExtValue() != 8)
3112 return false;
3113 }
3114 } else if (Opc == ISD::SHL) {
3115 // (x & 0xff) << 8
3116 // (x & 0xff0000) << 8
3117 if (Num != 0 && Num != 2)
3118 return false;
3119 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3120 if (!C || C->getZExtValue() != 8)
3121 return false;
3122 } else { // Opc == ISD::SRL
3123 // (x & 0xff00) >> 8
3124 // (x & 0xff000000) >> 8
3125 if (Num != 1 && Num != 3)
3126 return false;
3127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128 if (!C || C->getZExtValue() != 8)
3129 return false;
3130 }
3131
3132 if (Parts[Num])
3133 return false;
3134
3135 Parts[Num] = N0.getOperand(0).getNode();
3136 return true;
3137}
3138
3139/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3140/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3141/// => (rotl (bswap x), 16)
3142SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3143 if (!LegalOperations)
3144 return SDValue();
3145
3146 EVT VT = N->getValueType(0);
3147 if (VT != MVT::i32)
3148 return SDValue();
3149 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3150 return SDValue();
3151
Stephen Hinesdce4a402014-05-29 02:49:00 -07003152 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng9568e5c2011-06-21 06:01:08 +00003153 // Look for either
3154 // (or (or (and), (and)), (or (and), (and)))
3155 // (or (or (or (and), (and)), (and)), (and))
3156 if (N0.getOpcode() != ISD::OR)
3157 return SDValue();
3158 SDValue N00 = N0.getOperand(0);
3159 SDValue N01 = N0.getOperand(1);
3160
Evan Cheng9a65a012012-12-13 01:34:32 +00003161 if (N1.getOpcode() == ISD::OR &&
3162 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng9568e5c2011-06-21 06:01:08 +00003163 // (or (or (and), (and)), (or (and), (and)))
3164 SDValue N000 = N00.getOperand(0);
3165 if (!isBSwapHWordElement(N000, Parts))
3166 return SDValue();
3167
3168 SDValue N001 = N00.getOperand(1);
3169 if (!isBSwapHWordElement(N001, Parts))
3170 return SDValue();
3171 SDValue N010 = N01.getOperand(0);
3172 if (!isBSwapHWordElement(N010, Parts))
3173 return SDValue();
3174 SDValue N011 = N01.getOperand(1);
3175 if (!isBSwapHWordElement(N011, Parts))
3176 return SDValue();
3177 } else {
3178 // (or (or (or (and), (and)), (and)), (and))
3179 if (!isBSwapHWordElement(N1, Parts))
3180 return SDValue();
3181 if (!isBSwapHWordElement(N01, Parts))
3182 return SDValue();
3183 if (N00.getOpcode() != ISD::OR)
3184 return SDValue();
3185 SDValue N000 = N00.getOperand(0);
3186 if (!isBSwapHWordElement(N000, Parts))
3187 return SDValue();
3188 SDValue N001 = N00.getOperand(1);
3189 if (!isBSwapHWordElement(N001, Parts))
3190 return SDValue();
3191 }
3192
3193 // Make sure the parts are all coming from the same node.
3194 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3195 return SDValue();
3196
Andrew Trickac6d9be2013-05-25 02:42:55 +00003197 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00003198 SDValue(Parts[0],0));
3199
Kay Tiong Khoo670711e2013-09-23 18:43:51 +00003200 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng9568e5c2011-06-21 06:01:08 +00003201 // do (x << 16) | (x >> 16).
3202 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3203 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003204 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper0eb5dad2012-09-29 07:18:53 +00003205 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003206 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3207 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3208 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3209 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng9568e5c2011-06-21 06:01:08 +00003210}
3211
Dan Gohman475871a2008-07-27 21:46:04 +00003212SDValue DAGCombiner::visitOR(SDNode *N) {
3213 SDValue N0 = N->getOperand(0);
3214 SDValue N1 = N->getOperand(1);
3215 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman646d7e22005-09-02 21:18:40 +00003216 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003218 EVT VT = N1.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003219
Dan Gohman7f321562007-06-25 16:23:39 +00003220 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003221 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003222 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003223 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003224
3225 // fold (or x, 0) -> x, vector edition
3226 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3227 return N1;
3228 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3229 return N0;
3230
3231 // fold (or x, -1) -> -1, vector edition
3232 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3233 return N0;
3234 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3235 return N1;
Stephen Hines36b56882014-04-23 16:57:46 -07003236
3237 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3238 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3239 // Do this only if the resulting shuffle is legal.
3240 if (isa<ShuffleVectorSDNode>(N0) &&
3241 isa<ShuffleVectorSDNode>(N1) &&
3242 N0->getOperand(1) == N1->getOperand(1) &&
3243 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3244 bool CanFold = true;
3245 unsigned NumElts = VT.getVectorNumElements();
3246 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3247 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3248 // We construct two shuffle masks:
3249 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3250 // and N1 as the second operand.
3251 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3252 // and N0 as the second operand.
3253 // We do this because OR is commutable and therefore there might be
3254 // two ways to fold this node into a shuffle.
3255 SmallVector<int,4> Mask1;
3256 SmallVector<int,4> Mask2;
Stephen Hinesdce4a402014-05-29 02:49:00 -07003257
Stephen Hines36b56882014-04-23 16:57:46 -07003258 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3259 int M0 = SV0->getMaskElt(i);
3260 int M1 = SV1->getMaskElt(i);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003261
Stephen Hines36b56882014-04-23 16:57:46 -07003262 // Both shuffle indexes are undef. Propagate Undef.
3263 if (M0 < 0 && M1 < 0) {
3264 Mask1.push_back(M0);
3265 Mask2.push_back(M0);
3266 continue;
3267 }
3268
3269 if (M0 < 0 || M1 < 0 ||
3270 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3271 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3272 CanFold = false;
3273 break;
3274 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07003275
Stephen Hines36b56882014-04-23 16:57:46 -07003276 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3277 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3278 }
3279
3280 if (CanFold) {
3281 // Fold this sequence only if the resulting shuffle is 'legal'.
3282 if (TLI.isShuffleMaskLegal(Mask1, VT))
3283 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3284 N1->getOperand(0), &Mask1[0]);
3285 if (TLI.isShuffleMaskLegal(Mask2, VT))
3286 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3287 N0->getOperand(0), &Mask2[0]);
3288 }
3289 }
Dan Gohman05d92fe2007-07-13 20:03:40 +00003290 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003291
Dan Gohman613e0d82007-07-03 14:03:57 +00003292 // fold (or x, undef) -> -1
Bob Wilson86749492010-06-28 23:40:25 +00003293 if (!LegalOperations &&
3294 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman93e0ed32009-12-03 07:11:29 +00003295 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3296 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3297 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003298 // fold (or c1, c2) -> c1|c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003299 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003300 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003301 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003302 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003303 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003304 // fold (or x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003305 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003306 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003307 // fold (or x, -1) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00003308 if (N1C && N1C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003309 return N1;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003310 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003311 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begeman83e75ec2005-09-06 04:43:02 +00003312 return N1;
Evan Cheng9568e5c2011-06-21 06:01:08 +00003313
3314 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3315 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003316 if (BSwap.getNode())
Evan Cheng9568e5c2011-06-21 06:01:08 +00003317 return BSwap;
3318 BSwap = MatchBSwapHWordLow(N, N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003319 if (BSwap.getNode())
Evan Cheng9568e5c2011-06-21 06:01:08 +00003320 return BSwap;
3321
Nate Begemancd4d58c2006-02-03 06:46:56 +00003322 // reassociate or
Andrew Trickac6d9be2013-05-25 02:42:55 +00003323 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003324 if (ROR.getNode())
Nate Begemancd4d58c2006-02-03 06:46:56 +00003325 return ROR;
3326 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003327 // iff (c1 & c2) == 0.
Gabor Greifba36cb52008-08-28 21:40:38 +00003328 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattner731d3482005-10-27 05:06:38 +00003329 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattner731d3482005-10-27 05:06:38 +00003330 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003331 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3332 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3333 if (!COR.getNode())
3334 return SDValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00003335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3336 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Stephen Hines36b56882014-04-23 16:57:46 -07003337 N0.getOperand(0), N1), COR);
3338 }
Nate Begeman223df222005-09-08 20:18:10 +00003339 }
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003340 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3341 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3342 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3343 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00003344
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003345 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00003346 LL.getValueType().isInteger()) {
Bill Wendling09025642009-01-30 20:59:34 +00003347 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3348 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelfdc40a02009-02-17 22:15:04 +00003349 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003350 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003351 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003352 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003353 AddToWorkList(ORNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003354 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003355 }
Bill Wendling09025642009-01-30 20:59:34 +00003356 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3357 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelfdc40a02009-02-17 22:15:04 +00003358 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003359 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003360 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendling09025642009-01-30 20:59:34 +00003361 LR.getValueType(), LL, RL);
Gabor Greifba36cb52008-08-28 21:40:38 +00003362 AddToWorkList(ANDNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003363 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003364 }
3365 }
3366 // canonicalize equivalent to ll == rl
3367 if (LL == RR && LR == RL) {
3368 Op1 = ISD::getSetCCSwappedOperands(Op1);
3369 std::swap(RL, RR);
3370 }
3371 if (LL == RL && LR == RR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003372 bool isInteger = LL.getValueType().isInteger();
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003373 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner6e1c6232008-10-28 07:11:07 +00003374 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003375 (!LegalOperations ||
Owen Anderson39125d92013-02-14 09:07:33 +00003376 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3377 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +00003378 getSetCCResultType(N0.getValueType())))))
Andrew Trickac6d9be2013-05-25 02:42:55 +00003379 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling09025642009-01-30 20:59:34 +00003380 LL, LR, Result);
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003381 }
3382 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003383
Bill Wendling09025642009-01-30 20:59:34 +00003384 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner35e5c142006-05-05 05:51:50 +00003385 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003386 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003387 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003388 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003389
Bill Wendling09025642009-01-30 20:59:34 +00003390 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner1ec72732006-09-14 21:11:37 +00003391 if (N0.getOpcode() == ISD::AND &&
3392 N1.getOpcode() == ISD::AND &&
3393 N0.getOperand(1).getOpcode() == ISD::Constant &&
3394 N1.getOperand(1).getOpcode() == ISD::Constant &&
3395 // Don't increase # computations.
Gabor Greifba36cb52008-08-28 21:40:38 +00003396 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner1ec72732006-09-14 21:11:37 +00003397 // We can only do this xform if we know that bits from X that are set in C2
3398 // but not in C1 are already zero. Likewise for Y.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00003399 const APInt &LHSMask =
3400 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3401 const APInt &RHSMask =
3402 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003403
Dan Gohmanea859be2007-06-22 14:59:07 +00003404 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3405 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003406 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendling09025642009-01-30 20:59:34 +00003407 N0.getOperand(0), N1.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003408 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendling09025642009-01-30 20:59:34 +00003409 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner1ec72732006-09-14 21:11:37 +00003410 }
3411 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003412
Chris Lattner516b9622006-09-14 20:50:57 +00003413 // See if this is some rotate idiom.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003414 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman475871a2008-07-27 21:46:04 +00003415 return SDValue(Rot, 0);
Chris Lattner35e5c142006-05-05 05:51:50 +00003416
Dan Gohman4e39e9d2010-06-24 14:30:44 +00003417 // Simplify the operands using demanded-bits information.
3418 if (!VT.isVector() &&
3419 SimplifyDemandedBits(SDValue(N, 0)))
3420 return SDValue(N, 0);
3421
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003422 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003423}
3424
Chris Lattner516b9622006-09-14 20:50:57 +00003425/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003426static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner516b9622006-09-14 20:50:57 +00003427 if (Op.getOpcode() == ISD::AND) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00003428 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner516b9622006-09-14 20:50:57 +00003429 Mask = Op.getOperand(1);
3430 Op = Op.getOperand(0);
3431 } else {
3432 return false;
3433 }
3434 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003435
Chris Lattner516b9622006-09-14 20:50:57 +00003436 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3437 Shift = Op;
3438 return true;
3439 }
Bill Wendling09025642009-01-30 20:59:34 +00003440
Scott Michelfdc40a02009-02-17 22:15:04 +00003441 return false;
Chris Lattner516b9622006-09-14 20:50:57 +00003442}
3443
Stephen Hines36b56882014-04-23 16:57:46 -07003444// Return true if we can prove that, whenever Neg and Pos are both in the
3445// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3446// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3447//
3448// (or (shift1 X, Neg), (shift2 X, Pos))
3449//
3450// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3451// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3452// to consider shift amounts with defined behavior.
3453static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3454 // If OpSize is a power of 2 then:
3455 //
3456 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3457 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3458 //
3459 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3460 // for the stronger condition:
3461 //
3462 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3463 //
3464 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3465 // we can just replace Neg with Neg' for the rest of the function.
3466 //
3467 // In other cases we check for the even stronger condition:
3468 //
3469 // Neg == OpSize - Pos [B]
3470 //
3471 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3472 // behavior if Pos == 0 (and consequently Neg == OpSize).
3473 //
3474 // We could actually use [A] whenever OpSize is a power of 2, but the
3475 // only extra cases that it would match are those uninteresting ones
3476 // where Neg and Pos are never in range at the same time. E.g. for
3477 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3478 // as well as (sub 32, Pos), but:
3479 //
3480 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3481 //
3482 // always invokes undefined behavior for 32-bit X.
3483 //
3484 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3485 unsigned MaskLoBits = 0;
3486 if (Neg.getOpcode() == ISD::AND &&
3487 isPowerOf2_64(OpSize) &&
3488 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3489 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3490 Neg = Neg.getOperand(0);
3491 MaskLoBits = Log2_64(OpSize);
3492 }
3493
3494 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3495 if (Neg.getOpcode() != ISD::SUB)
3496 return 0;
3497 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3498 if (!NegC)
3499 return 0;
3500 SDValue NegOp1 = Neg.getOperand(1);
3501
3502 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3503 // Pos'. The truncation is redundant for the purpose of the equality.
3504 if (MaskLoBits &&
3505 Pos.getOpcode() == ISD::AND &&
3506 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3507 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3508 Pos = Pos.getOperand(0);
3509
3510 // The condition we need is now:
3511 //
3512 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3513 //
3514 // If NegOp1 == Pos then we need:
3515 //
3516 // OpSize & Mask == NegC & Mask
3517 //
3518 // (because "x & Mask" is a truncation and distributes through subtraction).
3519 APInt Width;
3520 if (Pos == NegOp1)
3521 Width = NegC->getAPIntValue();
3522 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3523 // Then the condition we want to prove becomes:
3524 //
3525 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3526 //
3527 // which, again because "x & Mask" is a truncation, becomes:
3528 //
3529 // NegC & Mask == (OpSize - PosC) & Mask
3530 // OpSize & Mask == (NegC + PosC) & Mask
3531 else if (Pos.getOpcode() == ISD::ADD &&
3532 Pos.getOperand(0) == NegOp1 &&
3533 Pos.getOperand(1).getOpcode() == ISD::Constant)
3534 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3535 NegC->getAPIntValue());
3536 else
3537 return false;
3538
3539 // Now we just need to check that OpSize & Mask == Width & Mask.
3540 if (MaskLoBits)
3541 // Opsize & Mask is 0 since Mask is Opsize - 1.
3542 return Width.getLoBits(MaskLoBits) == 0;
3543 return Width == OpSize;
3544}
3545
3546// A subroutine of MatchRotate used once we have found an OR of two opposite
3547// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3548// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3549// former being preferred if supported. InnerPos and InnerNeg are Pos and
3550// Neg with outer conversions stripped away.
3551SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3552 SDValue Neg, SDValue InnerPos,
3553 SDValue InnerNeg, unsigned PosOpcode,
3554 unsigned NegOpcode, SDLoc DL) {
3555 // fold (or (shl x, (*ext y)),
3556 // (srl x, (*ext (sub 32, y)))) ->
3557 // (rotl x, y) or (rotr x, (sub 32, y))
3558 //
3559 // fold (or (shl x, (*ext (sub 32, y))),
3560 // (srl x, (*ext y))) ->
3561 // (rotr x, y) or (rotl x, (sub 32, y))
3562 EVT VT = Shifted.getValueType();
3563 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3564 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3565 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3566 HasPos ? Pos : Neg).getNode();
3567 }
3568
Stephen Hinesdce4a402014-05-29 02:49:00 -07003569 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07003570}
3571
Chris Lattner516b9622006-09-14 20:50:57 +00003572// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3573// idioms for rotate, and if the target supports rotation instructions, generate
3574// a rot[lr].
Andrew Trickac6d9be2013-05-25 02:42:55 +00003575SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003576 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Andersone50ed302009-08-10 22:56:29 +00003577 EVT VT = LHS.getValueType();
Stephen Hinesdce4a402014-05-29 02:49:00 -07003578 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner516b9622006-09-14 20:50:57 +00003579
3580 // The target must have at least one rotate flavor.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00003581 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3582 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003583 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00003584
Chris Lattner516b9622006-09-14 20:50:57 +00003585 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman475871a2008-07-27 21:46:04 +00003586 SDValue LHSShift; // The shift.
3587 SDValue LHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003588 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Stephen Hinesdce4a402014-05-29 02:49:00 -07003589 return nullptr; // Not part of a rotate.
Chris Lattner516b9622006-09-14 20:50:57 +00003590
Dan Gohman475871a2008-07-27 21:46:04 +00003591 SDValue RHSShift; // The shift.
3592 SDValue RHSMask; // AND value if any.
Chris Lattner516b9622006-09-14 20:50:57 +00003593 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Stephen Hinesdce4a402014-05-29 02:49:00 -07003594 return nullptr; // Not part of a rotate.
Scott Michelfdc40a02009-02-17 22:15:04 +00003595
Chris Lattner516b9622006-09-14 20:50:57 +00003596 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Stephen Hinesdce4a402014-05-29 02:49:00 -07003597 return nullptr; // Not shifting the same value.
Chris Lattner516b9622006-09-14 20:50:57 +00003598
3599 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Stephen Hinesdce4a402014-05-29 02:49:00 -07003600 return nullptr; // Shifts must disagree.
Scott Michelfdc40a02009-02-17 22:15:04 +00003601
Chris Lattner516b9622006-09-14 20:50:57 +00003602 // Canonicalize shl to left side in a shl/srl pair.
3603 if (RHSShift.getOpcode() == ISD::SHL) {
3604 std::swap(LHS, RHS);
3605 std::swap(LHSShift, RHSShift);
3606 std::swap(LHSMask , RHSMask );
3607 }
3608
Duncan Sands83ec4b62008-06-06 12:08:01 +00003609 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman475871a2008-07-27 21:46:04 +00003610 SDValue LHSShiftArg = LHSShift.getOperand(0);
3611 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Stephen Hines36b56882014-04-23 16:57:46 -07003612 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00003613 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner516b9622006-09-14 20:50:57 +00003614
3615 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3616 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michelc9dc1142007-04-02 21:36:32 +00003617 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3618 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003619 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3620 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner516b9622006-09-14 20:50:57 +00003621 if ((LShVal + RShVal) != OpSizeInBits)
Stephen Hinesdce4a402014-05-29 02:49:00 -07003622 return nullptr;
Chris Lattner516b9622006-09-14 20:50:57 +00003623
Craig Topper32b73432012-09-29 06:54:22 +00003624 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3625 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelfdc40a02009-02-17 22:15:04 +00003626
Chris Lattner516b9622006-09-14 20:50:57 +00003627 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greifba36cb52008-08-28 21:40:38 +00003628 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelfdc40a02009-02-17 22:15:04 +00003630
Gabor Greifba36cb52008-08-28 21:40:38 +00003631 if (LHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003632 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3633 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003634 }
Gabor Greifba36cb52008-08-28 21:40:38 +00003635 if (RHSMask.getNode()) {
Dan Gohman220a8232008-03-03 23:51:38 +00003636 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3637 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner516b9622006-09-14 20:50:57 +00003638 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003639
Bill Wendling317bd702009-01-30 21:14:50 +00003640 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner516b9622006-09-14 20:50:57 +00003641 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003642
Gabor Greifba36cb52008-08-28 21:40:38 +00003643 return Rot.getNode();
Chris Lattner516b9622006-09-14 20:50:57 +00003644 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003645
Chris Lattner516b9622006-09-14 20:50:57 +00003646 // If there is a mask here, and we have a variable shift, we can't be sure
3647 // that we're masking out the right stuff.
Gabor Greifba36cb52008-08-28 21:40:38 +00003648 if (LHSMask.getNode() || RHSMask.getNode())
Stephen Hinesdce4a402014-05-29 02:49:00 -07003649 return nullptr;
Scott Michelfdc40a02009-02-17 22:15:04 +00003650
Benjamin Kramercd216b22013-09-24 14:21:28 +00003651 // If the shift amount is sign/zext/any-extended just peel it off.
3652 SDValue LExtOp0 = LHSShiftAmt;
3653 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper0eb5dad2012-09-29 07:18:53 +00003654 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3655 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3656 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3657 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3658 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3659 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3660 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3661 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramercd216b22013-09-24 14:21:28 +00003662 LExtOp0 = LHSShiftAmt.getOperand(0);
3663 RExtOp0 = RHSShiftAmt.getOperand(0);
3664 }
3665
Stephen Hines36b56882014-04-23 16:57:46 -07003666 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3667 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3668 if (TryL)
3669 return TryL;
3670
3671 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3672 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3673 if (TryR)
3674 return TryR;
Scott Michelfdc40a02009-02-17 22:15:04 +00003675
Stephen Hinesdce4a402014-05-29 02:49:00 -07003676 return nullptr;
Chris Lattner516b9622006-09-14 20:50:57 +00003677}
3678
Dan Gohman475871a2008-07-27 21:46:04 +00003679SDValue DAGCombiner::visitXOR(SDNode *N) {
3680 SDValue N0 = N->getOperand(0);
3681 SDValue N1 = N->getOperand(1);
3682 SDValue LHS, RHS, CC;
Nate Begeman646d7e22005-09-02 21:18:40 +00003683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003685 EVT VT = N0.getValueType();
Scott Michelfdc40a02009-02-17 22:15:04 +00003686
Dan Gohman7f321562007-06-25 16:23:39 +00003687 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00003688 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003689 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003690 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper9472b4f2012-12-08 22:49:19 +00003691
3692 // fold (xor x, 0) -> x, vector edition
3693 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3694 return N1;
3695 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3696 return N0;
Dan Gohman05d92fe2007-07-13 20:03:40 +00003697 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003698
Evan Cheng26471c42008-03-25 20:08:07 +00003699 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3700 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3701 return DAG.getConstant(0, VT);
Dan Gohman613e0d82007-07-03 14:03:57 +00003702 // fold (xor x, undef) -> undef
Dan Gohman70fb1ae2007-07-10 15:19:29 +00003703 if (N0.getOpcode() == ISD::UNDEF)
3704 return N0;
3705 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman613e0d82007-07-03 14:03:57 +00003706 return N1;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003707 // fold (xor c1, c2) -> c1^c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003708 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003709 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman99801192005-09-07 23:25:52 +00003710 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00003711 if (N0C && !N1C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003712 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003713 // fold (xor x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003714 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003715 return N0;
Nate Begemancd4d58c2006-02-03 06:46:56 +00003716 // reassociate xor
Andrew Trickac6d9be2013-05-25 02:42:55 +00003717 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07003718 if (RXOR.getNode())
Nate Begemancd4d58c2006-02-03 06:46:56 +00003719 return RXOR;
Bill Wendlingae89bb12008-11-11 08:25:46 +00003720
Nate Begeman1d4d4142005-09-01 00:19:25 +00003721 // fold !(x cc y) -> (x !cc y)
Dan Gohman002e5d02008-03-13 22:13:53 +00003722 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003723 bool isInt = LHS.getValueType().isInteger();
Nate Begeman646d7e22005-09-02 21:18:40 +00003724 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3725 isInt);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003726
Patrik Hagglundfdbeb052012-12-19 10:19:55 +00003727 if (!LegalOperations ||
3728 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendlingae89bb12008-11-11 08:25:46 +00003729 switch (N0.getOpcode()) {
3730 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003731 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendlingae89bb12008-11-11 08:25:46 +00003732 case ISD::SETCC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003733 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendlingae89bb12008-11-11 08:25:46 +00003734 case ISD::SELECT_CC:
Andrew Trickac6d9be2013-05-25 02:42:55 +00003735 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendlingae89bb12008-11-11 08:25:46 +00003736 N0.getOperand(3), NotCC);
3737 }
3738 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00003739 }
Bill Wendlingae89bb12008-11-11 08:25:46 +00003740
Chris Lattner61c5ff42007-09-10 21:39:07 +00003741 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman002e5d02008-03-13 22:13:53 +00003742 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greif12632d22008-08-30 19:29:20 +00003743 N0.getNode()->hasOneUse() &&
3744 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman475871a2008-07-27 21:46:04 +00003745 SDValue V = N0.getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003746 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands272dce02007-10-10 09:54:50 +00003747 DAG.getConstant(1, V.getValueType()));
Gabor Greifba36cb52008-08-28 21:40:38 +00003748 AddToWorkList(V.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003749 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner61c5ff42007-09-10 21:39:07 +00003750 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003751
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003752 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson825b72b2009-08-11 20:47:22 +00003753 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman99801192005-09-07 23:25:52 +00003754 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003755 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003756 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3757 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003758 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3759 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003760 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003761 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003762 }
3763 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00003764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelfdc40a02009-02-17 22:15:04 +00003765 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman99801192005-09-07 23:25:52 +00003766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman475871a2008-07-27 21:46:04 +00003767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman99801192005-09-07 23:25:52 +00003768 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickac6d9be2013-05-25 02:42:55 +00003770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greifba36cb52008-08-28 21:40:38 +00003772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003774 }
3775 }
David Majnemer363160a2013-05-08 06:44:42 +00003776 // fold (xor (and x, y), y) -> (and (not x), y)
3777 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerd5ae5b02013-11-17 10:40:03 +00003778 N0->getOperand(1) == N1) {
David Majnemer363160a2013-05-08 06:44:42 +00003779 SDValue X = N0->getOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003780 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer363160a2013-05-08 06:44:42 +00003781 AddToWorkList(NotX.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003782 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer363160a2013-05-08 06:44:42 +00003783 }
Bill Wendling317bd702009-01-30 21:14:50 +00003784 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman223df222005-09-08 20:18:10 +00003785 if (N1C && N0.getOpcode() == ISD::XOR) {
3786 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3787 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3788 if (N00C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003789 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling317bd702009-01-30 21:14:50 +00003790 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003791 N00C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003792 if (N01C)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003793 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling317bd702009-01-30 21:14:50 +00003794 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohman002e5d02008-03-13 22:13:53 +00003795 N01C->getAPIntValue(), VT));
Nate Begeman223df222005-09-08 20:18:10 +00003796 }
3797 // fold (xor x, x) -> 0
Eric Christopher7bccf6a2011-02-16 04:50:12 +00003798 if (N0 == N1)
Hal Finkelbd6f1f62013-07-09 17:02:45 +00003799 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelfdc40a02009-02-17 22:15:04 +00003800
Chris Lattner35e5c142006-05-05 05:51:50 +00003801 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3802 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003803 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00003804 if (Tmp.getNode()) return Tmp;
Nate Begeman39ee1ac2005-09-09 19:49:52 +00003805 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003806
Chris Lattner3e104b12006-04-08 04:15:24 +00003807 // Simplify the expression using non-local knowledge.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003808 if (!VT.isVector() &&
Dan Gohman475871a2008-07-27 21:46:04 +00003809 SimplifyDemandedBits(SDValue(N, 0)))
3810 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003811
Evan Chengb3a3d5e2010-04-28 07:10:39 +00003812 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00003813}
3814
Chris Lattnere70da202007-12-06 07:33:36 +00003815/// visitShiftByConstant - Handle transforms common to the three shifts, when
3816/// the shift amount is a constant.
Stephen Hines36b56882014-04-23 16:57:46 -07003817SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3818 // We can't and shouldn't fold opaque constants.
3819 if (Amt->isOpaque())
3820 return SDValue();
3821
Gabor Greifba36cb52008-08-28 21:40:38 +00003822 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman475871a2008-07-27 21:46:04 +00003823 if (!LHS->hasOneUse()) return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003824
Chris Lattnere70da202007-12-06 07:33:36 +00003825 // We want to pull some binops through shifts, so that we have (and (shift))
3826 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3827 // thing happens with address calculations, so it's important to canonicalize
3828 // it.
3829 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelfdc40a02009-02-17 22:15:04 +00003830
Chris Lattnere70da202007-12-06 07:33:36 +00003831 switch (LHS->getOpcode()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003832 default: return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003833 case ISD::OR:
3834 case ISD::XOR:
3835 HighBitSet = false; // We can only transform sra if the high bit is clear.
3836 break;
3837 case ISD::AND:
3838 HighBitSet = true; // We can only transform sra if the high bit is set.
3839 break;
3840 case ISD::ADD:
Scott Michelfdc40a02009-02-17 22:15:04 +00003841 if (N->getOpcode() != ISD::SHL)
Dan Gohman475871a2008-07-27 21:46:04 +00003842 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattnere70da202007-12-06 07:33:36 +00003843 HighBitSet = false; // We can only transform sra if the high bit is clear.
3844 break;
3845 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003846
Stephen Hines36b56882014-04-23 16:57:46 -07003847 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattnere70da202007-12-06 07:33:36 +00003848 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003849 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendling88103372009-01-30 21:37:17 +00003850
3851 // FIXME: disable this unless the input to the binop is a shift by a constant.
3852 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003853 //
Bill Wendling88103372009-01-30 21:37:17 +00003854 // void foo(int *X, int i) { X[i & 1235] = 1; }
3855 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greifba36cb52008-08-28 21:40:38 +00003856 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00003857 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnerd3fd6d22007-12-06 07:47:55 +00003858 BinOpLHSVal->getOpcode() != ISD::SRA &&
3859 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3860 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman475871a2008-07-27 21:46:04 +00003861 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00003862
Owen Andersone50ed302009-08-10 22:56:29 +00003863 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00003864
Bill Wendling88103372009-01-30 21:37:17 +00003865 // If this is a signed shift right, and the high bit is modified by the
3866 // logical operation, do not perform the transformation. The highBitSet
3867 // boolean indicates the value of the high bit of the constant which would
3868 // cause it to be modified for this operation.
Chris Lattnere70da202007-12-06 07:33:36 +00003869 if (N->getOpcode() == ISD::SRA) {
Dan Gohman220a8232008-03-03 23:51:38 +00003870 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3871 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman475871a2008-07-27 21:46:04 +00003872 return SDValue();
Chris Lattnere70da202007-12-06 07:33:36 +00003873 }
Scott Michelfdc40a02009-02-17 22:15:04 +00003874
Stephen Hinesdce4a402014-05-29 02:49:00 -07003875 if (!TLI.isDesirableToCommuteWithShift(LHS))
3876 return SDValue();
3877
Chris Lattnere70da202007-12-06 07:33:36 +00003878 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003879 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendling88103372009-01-30 21:37:17 +00003880 N->getValueType(0),
3881 LHS->getOperand(1), N->getOperand(1));
Stephen Hines36b56882014-04-23 16:57:46 -07003882 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattnere70da202007-12-06 07:33:36 +00003883
3884 // Create the new shift.
Eric Christopher503a64d2010-12-09 04:48:06 +00003885 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00003886 SDLoc(LHS->getOperand(0)),
Bill Wendling88103372009-01-30 21:37:17 +00003887 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattnere70da202007-12-06 07:33:36 +00003888
3889 // Create the new binop.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003890 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattnere70da202007-12-06 07:33:36 +00003891}
3892
Stephen Hines36b56882014-04-23 16:57:46 -07003893SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3894 assert(N->getOpcode() == ISD::TRUNCATE);
3895 assert(N->getOperand(0).getOpcode() == ISD::AND);
3896
3897 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3898 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3899 SDValue N01 = N->getOperand(0).getOperand(1);
3900
3901 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3902 EVT TruncVT = N->getValueType(0);
3903 SDValue N00 = N->getOperand(0).getOperand(0);
3904 APInt TruncC = N01C->getAPIntValue();
3905 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3906
3907 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3908 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3909 DAG.getConstant(TruncC, TruncVT));
3910 }
3911 }
3912
3913 return SDValue();
3914}
3915
3916SDValue DAGCombiner::visitRotate(SDNode *N) {
3917 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3918 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3919 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3920 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3921 if (NewOp1.getNode())
3922 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3923 N->getOperand(0), NewOp1);
3924 }
3925 return SDValue();
3926}
3927
Dan Gohman475871a2008-07-27 21:46:04 +00003928SDValue DAGCombiner::visitSHL(SDNode *N) {
3929 SDValue N0 = N->getOperand(0);
3930 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00003931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00003933 EVT VT = N0.getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -07003934 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00003935
Daniel Sanders028e4d22013-11-11 17:23:41 +00003936 // fold vector ops
3937 if (VT.isVector()) {
3938 SDValue FoldedVOp = SimplifyVBinOp(N);
3939 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07003940
3941 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3942 // If setcc produces all-one true value then:
3943 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3944 if (N1CV && N1CV->isConstant()) {
3945 if (N0.getOpcode() == ISD::AND &&
3946 TLI.getBooleanContents(true) ==
3947 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3948 SDValue N00 = N0->getOperand(0);
3949 SDValue N01 = N0->getOperand(1);
3950 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3951
3952 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3953 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3954 if (C.getNode())
3955 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3956 }
3957 } else {
3958 N1C = isConstOrConstSplat(N1);
3959 }
3960 }
Daniel Sanders028e4d22013-11-11 17:23:41 +00003961 }
3962
Nate Begeman1d4d4142005-09-01 00:19:25 +00003963 // fold (shl c1, c2) -> c1<<c2
Nate Begeman646d7e22005-09-02 21:18:40 +00003964 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00003965 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003966 // fold (shl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00003967 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003968 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00003969 // fold (shl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003970 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00003971 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003972 // fold (shl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00003973 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00003974 return N0;
Chad Rosier92bcd962011-06-14 22:29:10 +00003975 // fold (shl undef, x) -> 0
3976 if (N0.getOpcode() == ISD::UNDEF)
3977 return DAG.getConstant(0, VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00003978 // if (shl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00003979 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman87862e72009-12-11 21:31:27 +00003980 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00003981 return DAG.getConstant(0, VT);
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00003982 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00003983 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07003984 N1.getOperand(0).getOpcode() == ISD::AND) {
3985 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3986 if (NewOp1.getNode())
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00003988 }
3989
Dan Gohman475871a2008-07-27 21:46:04 +00003990 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3991 return SDValue(N, 0);
Bill Wendling88103372009-01-30 21:37:17 +00003992
3993 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Stephen Hines36b56882014-04-23 16:57:46 -07003994 if (N1C && N0.getOpcode() == ISD::SHL) {
3995 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3996 uint64_t c1 = N0C1->getZExtValue();
3997 uint64_t c2 = N1C->getZExtValue();
3998 if (c1 + c2 >= OpSizeInBits)
3999 return DAG.getConstant(0, VT);
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4001 DAG.getConstant(c1 + c2, N1.getValueType()));
4002 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004003 }
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004004
4005 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4006 // For this to be valid, the second form must not preserve any of the bits
4007 // that are shifted out by the inner shift in the first form. This means
4008 // the outer shift size must be >= the number of bits added by the ext.
4009 // As a corollary, we don't care what kind of ext it is.
4010 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4011 N0.getOpcode() == ISD::ANY_EXTEND ||
4012 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Stephen Hines36b56882014-04-23 16:57:46 -07004013 N0.getOperand(0).getOpcode() == ISD::SHL) {
4014 SDValue N0Op0 = N0.getOperand(0);
4015 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4016 uint64_t c1 = N0Op0C1->getZExtValue();
4017 uint64_t c2 = N1C->getZExtValue();
4018 EVT InnerShiftVT = N0Op0.getValueType();
4019 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4020 if (c2 >= OpSizeInBits - InnerShiftSize) {
4021 if (c1 + c2 >= OpSizeInBits)
4022 return DAG.getConstant(0, VT);
4023 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4024 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4025 N0Op0->getOperand(0)),
4026 DAG.getConstant(c1 + c2, N1.getValueType()));
4027 }
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004028 }
4029 }
4030
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00004031 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4032 // Only fold this if the inner zext has no other uses to avoid increasing
4033 // the total number of instructions.
4034 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Stephen Hines36b56882014-04-23 16:57:46 -07004035 N0.getOperand(0).getOpcode() == ISD::SRL) {
4036 SDValue N0Op0 = N0.getOperand(0);
4037 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4038 uint64_t c1 = N0Op0C1->getZExtValue();
4039 if (c1 < VT.getScalarSizeInBits()) {
4040 uint64_t c2 = N1C->getZExtValue();
4041 if (c1 == c2) {
4042 SDValue NewOp0 = N0.getOperand(0);
4043 EVT CountVT = NewOp0.getOperand(1).getValueType();
4044 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4045 NewOp0, DAG.getConstant(c2, CountVT));
4046 AddToWorkList(NewSHL.getNode());
4047 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4048 }
Andrea Di Biagioa9f113d2013-09-27 11:37:05 +00004049 }
4050 }
4051 }
4052
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00004053 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4054 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruth62dfc512012-01-05 11:05:55 +00004055 // Only fold this if the inner shift has no other uses -- if it does, folding
4056 // this will increase the total number of instructions.
Stephen Hines36b56882014-04-23 16:57:46 -07004057 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4058 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4059 uint64_t c1 = N0C1->getZExtValue();
4060 if (c1 < OpSizeInBits) {
4061 uint64_t c2 = N1C->getZExtValue();
4062 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4063 SDValue Shift;
4064 if (c2 > c1) {
4065 Mask = Mask.shl(c2 - c1);
4066 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4067 DAG.getConstant(c2 - c1, N1.getValueType()));
4068 } else {
4069 Mask = Mask.lshr(c1 - c2);
4070 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4071 DAG.getConstant(c1 - c2, N1.getValueType()));
4072 }
4073 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4074 DAG.getConstant(Mask, VT));
Eli Friedman2a6d9eb2011-06-09 22:14:44 +00004075 }
Evan Chengd101a722009-07-21 05:40:15 +00004076 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004077 }
Bill Wendling88103372009-01-30 21:37:17 +00004078 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004079 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Stephen Hines36b56882014-04-23 16:57:46 -07004080 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004081 SDValue HiBitsMask =
Stephen Hines36b56882014-04-23 16:57:46 -07004082 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4083 BitSize - N1C->getZExtValue()), VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004084 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00004085 HiBitsMask);
4086 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004087
Evan Chenge5b51ac2010-04-17 06:13:15 +00004088 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004089 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chenge5b51ac2010-04-17 06:13:15 +00004090 if (NewSHL.getNode())
4091 return NewSHL;
4092 }
4093
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004094 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004095}
4096
Dan Gohman475871a2008-07-27 21:46:04 +00004097SDValue DAGCombiner::visitSRA(SDNode *N) {
4098 SDValue N0 = N->getOperand(0);
4099 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00004100 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00004102 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00004103 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00004104
Daniel Sanders028e4d22013-11-11 17:23:41 +00004105 // fold vector ops
4106 if (VT.isVector()) {
4107 SDValue FoldedVOp = SimplifyVBinOp(N);
4108 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07004109
4110 N1C = isConstOrConstSplat(N1);
Daniel Sanders028e4d22013-11-11 17:23:41 +00004111 }
4112
Bill Wendling88103372009-01-30 21:37:17 +00004113 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman646d7e22005-09-02 21:18:40 +00004114 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00004115 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004116 // fold (sra 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004117 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004118 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004119 // fold (sra -1, x) -> -1
Nate Begeman646d7e22005-09-02 21:18:40 +00004120 if (N0C && N0C->isAllOnesValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004121 return N0;
Bill Wendling88103372009-01-30 21:37:17 +00004122 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman87862e72009-12-11 21:31:27 +00004123 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004124 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004125 // fold (sra x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004126 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004127 return N0;
Nate Begemanfb7217b2006-02-17 19:54:08 +00004128 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4129 // sext_inreg.
4130 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman87862e72009-12-11 21:31:27 +00004131 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohmand1996362010-01-09 02:13:55 +00004132 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4133 if (VT.isVector())
4134 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4135 ExtVT, VT.getVectorNumElements());
4136 if ((!LegalOperations ||
4137 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004138 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohmand1996362010-01-09 02:13:55 +00004139 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb7217b2006-02-17 19:54:08 +00004140 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004141
Bill Wendling88103372009-01-30 21:37:17 +00004142 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner71d9ebc2006-02-28 06:23:04 +00004143 if (N1C && N0.getOpcode() == ISD::SRA) {
Stephen Hines36b56882014-04-23 16:57:46 -07004144 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004145 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Stephen Hines36b56882014-04-23 16:57:46 -07004146 if (Sum >= OpSizeInBits)
4147 Sum = OpSizeInBits - 1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00004148 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Stephen Hines36b56882014-04-23 16:57:46 -07004149 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner71d9ebc2006-02-28 06:23:04 +00004150 }
4151 }
Christopher Lamb15cbde32008-03-19 08:30:06 +00004152
Bill Wendling88103372009-01-30 21:37:17 +00004153 // fold (sra (shl X, m), (sub result_size, n))
4154 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelfdc40a02009-02-17 22:15:04 +00004155 // result_size - n != m.
4156 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lambb9b04282008-03-20 04:31:39 +00004157 // code.
Stephen Hines36b56882014-04-23 16:57:46 -07004158 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb15cbde32008-03-19 08:30:06 +00004159 // Get the two constanst of the shifts, CN0 = m, CN = n.
Stephen Hines36b56882014-04-23 16:57:46 -07004160 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4161 if (N01C) {
4162 LLVMContext &Ctx = *DAG.getContext();
Christopher Lambb9b04282008-03-20 04:31:39 +00004163 // Determine what the truncate's result bitsize and type would be.
Stephen Hines36b56882014-04-23 16:57:46 -07004164 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4165
4166 if (VT.isVector())
4167 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4168
Christopher Lambb9b04282008-03-20 04:31:39 +00004169 // Determine the residual right-shift amount.
Torok Edwin6bb49582009-05-23 17:29:48 +00004170 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004171
Scott Michelfdc40a02009-02-17 22:15:04 +00004172 // If the shift is not a no-op (in which case this should be just a sign
4173 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohmanf451cb82010-02-10 16:03:48 +00004174 // on that type, and the truncate to that type is both legal and free,
Christopher Lambb9b04282008-03-20 04:31:39 +00004175 // perform the transform.
Torok Edwin6bb49582009-05-23 17:29:48 +00004176 if ((ShiftAmt > 0) &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00004177 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4178 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng260e07e2008-03-20 02:18:41 +00004179 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lambb9b04282008-03-20 04:31:39 +00004180
Owen Anderson95771af2011-02-25 21:41:48 +00004181 SDValue Amt = DAG.getConstant(ShiftAmt,
4182 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004183 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendling88103372009-01-30 21:37:17 +00004184 N0.getOperand(0), Amt);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendling88103372009-01-30 21:37:17 +00004186 Shift);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004187 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendling88103372009-01-30 21:37:17 +00004188 N->getValueType(0), Trunc);
Christopher Lamb15cbde32008-03-19 08:30:06 +00004189 }
4190 }
4191 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004192
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004193 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004194 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07004195 N1.getOperand(0).getOpcode() == ISD::AND) {
4196 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4197 if (NewOp1.getNode())
4198 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00004199 }
4200
Stephen Hines36b56882014-04-23 16:57:46 -07004201 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004202 // if c1 is equal to the number of bits the trunc removes
4203 if (N0.getOpcode() == ISD::TRUNCATE &&
4204 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4205 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4206 N0.getOperand(0).hasOneUse() &&
4207 N0.getOperand(0).getOperand(1).hasOneUse() &&
Stephen Hines36b56882014-04-23 16:57:46 -07004208 N1C) {
4209 SDValue N0Op0 = N0.getOperand(0);
4210 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4211 unsigned LargeShiftVal = LargeShift->getZExtValue();
4212 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004213
Stephen Hines36b56882014-04-23 16:57:46 -07004214 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4215 SDValue Amt =
4216 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4217 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4218 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4219 N0Op0.getOperand(0), Amt);
4220 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4221 }
Benjamin Kramer9b108a32011-01-30 16:38:43 +00004222 }
4223 }
4224
Scott Michelfdc40a02009-02-17 22:15:04 +00004225 // Simplify, based on bits shifted out of the LHS.
Dan Gohman475871a2008-07-27 21:46:04 +00004226 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4227 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004228
4229
Nate Begeman1d4d4142005-09-01 00:19:25 +00004230 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00004231 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004232 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattnere70da202007-12-06 07:33:36 +00004233
Evan Chenge5b51ac2010-04-17 06:13:15 +00004234 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004235 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chenge5b51ac2010-04-17 06:13:15 +00004236 if (NewSRA.getNode())
4237 return NewSRA;
4238 }
4239
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004240 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004241}
4242
Dan Gohman475871a2008-07-27 21:46:04 +00004243SDValue DAGCombiner::visitSRL(SDNode *N) {
4244 SDValue N0 = N->getOperand(0);
4245 SDValue N1 = N->getOperand(1);
Nate Begeman646d7e22005-09-02 21:18:40 +00004246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00004248 EVT VT = N0.getValueType();
Dan Gohman87862e72009-12-11 21:31:27 +00004249 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00004250
Daniel Sanders028e4d22013-11-11 17:23:41 +00004251 // fold vector ops
4252 if (VT.isVector()) {
4253 SDValue FoldedVOp = SimplifyVBinOp(N);
4254 if (FoldedVOp.getNode()) return FoldedVOp;
Stephen Hines36b56882014-04-23 16:57:46 -07004255
4256 N1C = isConstOrConstSplat(N1);
Daniel Sanders028e4d22013-11-11 17:23:41 +00004257 }
4258
Nate Begeman1d4d4142005-09-01 00:19:25 +00004259 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman646d7e22005-09-02 21:18:40 +00004260 if (N0C && N1C)
Bill Wendlingf3cbca22008-09-24 10:25:02 +00004261 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004262 // fold (srl 0, x) -> 0
Nate Begeman646d7e22005-09-02 21:18:40 +00004263 if (N0C && N0C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004264 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004265 // fold (srl x, c >= size(x)) -> undef
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004266 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesene8d72302009-02-06 23:05:02 +00004267 return DAG.getUNDEF(VT);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004268 // fold (srl x, 0) -> x
Nate Begeman646d7e22005-09-02 21:18:40 +00004269 if (N1C && N1C->isNullValue())
Nate Begeman83e75ec2005-09-06 04:43:02 +00004270 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00004271 // if (srl x, c) is known to be zero, return 0
Dan Gohman475871a2008-07-27 21:46:04 +00004272 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman2e68b6f2008-02-25 21:11:39 +00004273 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begeman83e75ec2005-09-06 04:43:02 +00004274 return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004275
Bill Wendling88103372009-01-30 21:37:17 +00004276 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Stephen Hines36b56882014-04-23 16:57:46 -07004277 if (N1C && N0.getOpcode() == ISD::SRL) {
4278 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4279 uint64_t c1 = N01C->getZExtValue();
4280 uint64_t c2 = N1C->getZExtValue();
4281 if (c1 + c2 >= OpSizeInBits)
4282 return DAG.getConstant(0, VT);
4283 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4284 DAG.getConstant(c1 + c2, N1.getValueType()));
4285 }
Nate Begeman1d4d4142005-09-01 00:19:25 +00004286 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004287
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004288 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004289 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4290 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004291 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Anderson95771af2011-02-25 21:41:48 +00004292 uint64_t c1 =
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004293 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004295 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4296 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004297 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen025cc6e2010-12-20 20:10:50 +00004298 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004299 if (c1 + OpSizeInBits == InnerShiftSize) {
4300 if (c1 + c2 >= InnerShiftSize)
4301 return DAG.getConstant(0, VT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004302 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4303 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004304 N0.getOperand(0)->getOperand(0),
Dale Johannesenc72b18c2010-12-21 21:55:50 +00004305 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesenf5daf8b2010-12-17 21:45:49 +00004306 }
4307 }
4308
Chris Lattnerefcddc32010-04-15 05:28:43 +00004309 // fold (srl (shl x, c), c) -> (and x, cst2)
Stephen Hines36b56882014-04-23 16:57:46 -07004310 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4311 unsigned BitSize = N0.getScalarValueSizeInBits();
4312 if (BitSize <= 64) {
4313 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4314 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4315 DAG.getConstant(~0ULL >> ShAmt, VT));
4316 }
Chris Lattnerefcddc32010-04-15 05:28:43 +00004317 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004318
Michael Liao2da86392013-06-21 18:45:27 +00004319 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner06afe072006-05-05 22:53:17 +00004320 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4321 // Shifting in all undef bits?
Owen Andersone50ed302009-08-10 22:56:29 +00004322 EVT SmallVT = N0.getOperand(0).getValueType();
Stephen Hines36b56882014-04-23 16:57:46 -07004323 unsigned BitSize = SmallVT.getScalarSizeInBits();
4324 if (N1C->getZExtValue() >= BitSize)
Dale Johannesene8d72302009-02-06 23:05:02 +00004325 return DAG.getUNDEF(VT);
Chris Lattner06afe072006-05-05 22:53:17 +00004326
Evan Chenge5b51ac2010-04-17 06:13:15 +00004327 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona34d9362011-04-14 17:30:49 +00004328 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004329 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona34d9362011-04-14 17:30:49 +00004330 N0.getOperand(0),
4331 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004332 AddToWorkList(SmallShift.getNode());
Stephen Hines36b56882014-04-23 16:57:46 -07004333 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao2da86392013-06-21 18:45:27 +00004334 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4335 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4336 DAG.getConstant(Mask, VT));
Evan Chenge5b51ac2010-04-17 06:13:15 +00004337 }
Chris Lattner06afe072006-05-05 22:53:17 +00004338 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004339
Chris Lattner3657ffe2006-10-12 20:23:19 +00004340 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4341 // bit, which is unmodified by sra.
Stephen Hines36b56882014-04-23 16:57:46 -07004342 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner3657ffe2006-10-12 20:23:19 +00004343 if (N0.getOpcode() == ISD::SRA)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004344 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner3657ffe2006-10-12 20:23:19 +00004345 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004346
Sylvestre Ledru94c22712012-09-27 10:14:43 +00004347 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelfdc40a02009-02-17 22:15:04 +00004348 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Stephen Hines36b56882014-04-23 16:57:46 -07004349 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohman948d8ea2008-02-20 16:33:30 +00004350 APInt KnownZero, KnownOne;
Stephen Hinesdce4a402014-05-29 02:49:00 -07004351 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelfdc40a02009-02-17 22:15:04 +00004352
Chris Lattner350bec02006-04-02 06:11:11 +00004353 // If any of the input bits are KnownOne, then the input couldn't be all
4354 // zeros, thus the result of the srl will always be zero.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004355 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004356
Chris Lattner350bec02006-04-02 06:11:11 +00004357 // If all of the bits input the to ctlz node are known to be zero, then
4358 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00004359 APInt UnknownBits = ~KnownZero;
Chris Lattner350bec02006-04-02 06:11:11 +00004360 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00004361
Chris Lattner350bec02006-04-02 06:11:11 +00004362 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendling88103372009-01-30 21:37:17 +00004363 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner350bec02006-04-02 06:11:11 +00004364 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendling88103372009-01-30 21:37:17 +00004365 // could be set on input to the CTLZ node. If this bit is set, the SRL
4366 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4367 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohman948d8ea2008-02-20 16:33:30 +00004368 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman475871a2008-07-27 21:46:04 +00004369 SDValue Op = N0.getOperand(0);
Bill Wendling88103372009-01-30 21:37:17 +00004370
Chris Lattner350bec02006-04-02 06:11:11 +00004371 if (ShAmt) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004372 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Anderson95771af2011-02-25 21:41:48 +00004373 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +00004374 AddToWorkList(Op.getNode());
Chris Lattner350bec02006-04-02 06:11:11 +00004375 }
Bill Wendling88103372009-01-30 21:37:17 +00004376
Andrew Trickac6d9be2013-05-25 02:42:55 +00004377 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling88103372009-01-30 21:37:17 +00004378 Op, DAG.getConstant(1, VT));
Chris Lattner350bec02006-04-02 06:11:11 +00004379 }
4380 }
Evan Chengeb9f8922008-08-30 02:03:58 +00004381
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00004382 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengeb9f8922008-08-30 02:03:58 +00004383 if (N1.getOpcode() == ISD::TRUNCATE &&
Stephen Hines36b56882014-04-23 16:57:46 -07004384 N1.getOperand(0).getOpcode() == ISD::AND) {
4385 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4386 if (NewOp1.getNode())
4387 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengeb9f8922008-08-30 02:03:58 +00004388 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004389
Chris Lattner61a4c072007-04-18 03:06:49 +00004390 // fold operands of srl based on knowledge that the low bits are not
4391 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00004392 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4393 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004394
Evan Cheng9ab2b982009-12-18 21:31:31 +00004395 if (N1C) {
Stephen Hines36b56882014-04-23 16:57:46 -07004396 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Cheng9ab2b982009-12-18 21:31:31 +00004397 if (NewSRL.getNode())
4398 return NewSRL;
4399 }
4400
Dan Gohman4e39e9d2010-06-24 14:30:44 +00004401 // Attempt to convert a srl of a load into a narrower zero-extending load.
4402 SDValue NarrowLoad = ReduceLoadWidth(N);
4403 if (NarrowLoad.getNode())
4404 return NarrowLoad;
4405
Evan Cheng9ab2b982009-12-18 21:31:31 +00004406 // Here is a common situation. We want to optimize:
4407 //
4408 // %a = ...
4409 // %b = and i32 %a, 2
4410 // %c = srl i32 %b, 1
4411 // brcond i32 %c ...
4412 //
4413 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004414 //
Evan Cheng9ab2b982009-12-18 21:31:31 +00004415 // %a = ...
4416 // %b = and %a, 2
4417 // %c = setcc eq %b, 0
4418 // brcond %c ...
4419 //
4420 // However when after the source operand of SRL is optimized into AND, the SRL
4421 // itself may not be optimized further. Look for it and add the BRCOND into
4422 // the worklist.
Evan Chengd40d03e2010-01-06 19:38:29 +00004423 if (N->hasOneUse()) {
4424 SDNode *Use = *N->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4426 AddToWorkList(Use);
4427 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4428 // Also look pass the truncate.
4429 Use = *Use->use_begin();
4430 if (Use->getOpcode() == ISD::BRCOND)
4431 AddToWorkList(Use);
4432 }
4433 }
Evan Cheng9ab2b982009-12-18 21:31:31 +00004434
Evan Chengb3a3d5e2010-04-28 07:10:39 +00004435 return SDValue();
Evan Cheng4c26e932010-04-19 19:29:22 +00004436}
4437
Dan Gohman475871a2008-07-27 21:46:04 +00004438SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4439 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004440 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004441
4442 // fold (ctlz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004443 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004444 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004445 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004446}
4447
Chandler Carruth63974b22011-12-13 01:56:10 +00004448SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4449 SDValue N0 = N->getOperand(0);
4450 EVT VT = N->getValueType(0);
4451
4452 // fold (ctlz_zero_undef c1) -> c2
4453 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004454 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004455 return SDValue();
4456}
4457
Dan Gohman475871a2008-07-27 21:46:04 +00004458SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4459 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004460 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004461
Nate Begeman1d4d4142005-09-01 00:19:25 +00004462 // fold (cttz c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004463 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004464 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004465 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004466}
4467
Chandler Carruth63974b22011-12-13 01:56:10 +00004468SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4469 SDValue N0 = N->getOperand(0);
4470 EVT VT = N->getValueType(0);
4471
4472 // fold (cttz_zero_undef c1) -> c2
4473 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004474 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth63974b22011-12-13 01:56:10 +00004475 return SDValue();
4476}
4477
Dan Gohman475871a2008-07-27 21:46:04 +00004478SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4479 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004480 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004481
Nate Begeman1d4d4142005-09-01 00:19:25 +00004482 // fold (ctpop c1) -> c2
Chris Lattner310b5782006-05-06 23:06:26 +00004483 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004484 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman475871a2008-07-27 21:46:04 +00004485 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00004486}
4487
Dan Gohman475871a2008-07-27 21:46:04 +00004488SDValue DAGCombiner::visitSELECT(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 SDValue N2 = N->getOperand(2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004492 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Andersone50ed302009-08-10 22:56:29 +00004495 EVT VT = N->getValueType(0);
4496 EVT VT0 = N0.getValueType();
Nate Begeman44728a72005-09-19 22:34:01 +00004497
Bill Wendling34584e62009-01-30 22:02:18 +00004498 // fold (select C, X, X) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004499 if (N1 == N2)
4500 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004501 // fold (select true, X, Y) -> X
Nate Begeman452d7be2005-09-16 00:54:12 +00004502 if (N0C && !N0C->isNullValue())
4503 return N1;
Bill Wendling34584e62009-01-30 22:02:18 +00004504 // fold (select false, X, Y) -> Y
Nate Begeman452d7be2005-09-16 00:54:12 +00004505 if (N0C && N0C->isNullValue())
4506 return N2;
Bill Wendling34584e62009-01-30 22:02:18 +00004507 // fold (select C, 1, X) -> (or C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004508 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004509 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004510 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilson67ba2232009-01-22 22:05:48 +00004511 if (VT.isInteger() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00004512 (VT0 == MVT::i1 ||
Bob Wilson67ba2232009-01-22 22:05:48 +00004513 (VT0.isInteger() &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00004514 TLI.getBooleanContents(false) ==
4515 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00004516 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendling34584e62009-01-30 22:02:18 +00004517 SDValue XORNode;
Evan Cheng571c4782007-08-18 05:57:05 +00004518 if (VT == VT0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004519 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004520 N0, DAG.getConstant(1, VT0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004521 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendling34584e62009-01-30 22:02:18 +00004522 N0, DAG.getConstant(1, VT0));
Gabor Greifba36cb52008-08-28 21:40:38 +00004523 AddToWorkList(XORNode.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00004524 if (VT.bitsGT(VT0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004525 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Cheng571c4782007-08-18 05:57:05 +00004527 }
Bill Wendling34584e62009-01-30 22:02:18 +00004528 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004529 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004530 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004531 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004532 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman452d7be2005-09-16 00:54:12 +00004533 }
Bill Wendling34584e62009-01-30 22:02:18 +00004534 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004535 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004536 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilson4c245462009-01-22 17:39:32 +00004537 AddToWorkList(NOTNode.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004538 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman452d7be2005-09-16 00:54:12 +00004539 }
Bill Wendling34584e62009-01-30 22:02:18 +00004540 // fold (select C, X, 0) -> (and C, X)
Owen Anderson825b72b2009-08-11 20:47:22 +00004541 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickac6d9be2013-05-25 02:42:55 +00004542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendling34584e62009-01-30 22:02:18 +00004543 // fold (select X, X, Y) -> (or X, Y)
4544 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004545 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004546 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendling34584e62009-01-30 22:02:18 +00004547 // fold (select X, Y, X) -> (and X, Y)
4548 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson825b72b2009-08-11 20:47:22 +00004549 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004550 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00004551
Chris Lattner40c62d52005-10-18 06:04:22 +00004552 // If we can fold this based on the true/false value, do so.
4553 if (SimplifySelectOps(N, N1, N2))
Dan Gohman475871a2008-07-27 21:46:04 +00004554 return SDValue(N, 0); // Don't revisit N.
Duncan Sandsd4b9c172008-06-13 19:07:40 +00004555
Nate Begeman44728a72005-09-19 22:34:01 +00004556 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004557 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman750ac1b2006-02-01 07:19:44 +00004558 // FIXME:
Owen Anderson825b72b2009-08-11 20:47:22 +00004559 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman750ac1b2006-02-01 07:19:44 +00004560 // having to say they don't support SELECT_CC on every type the DAG knows
4561 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson825b72b2009-08-11 20:47:22 +00004562 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman4ea48042009-08-02 16:19:38 +00004563 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00004564 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendling34584e62009-01-30 22:02:18 +00004565 N0.getOperand(0), N0.getOperand(1),
Nate Begeman750ac1b2006-02-01 07:19:44 +00004566 N1, N2, N0.getOperand(2));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004567 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00004568 }
Bill Wendling34584e62009-01-30 22:02:18 +00004569
Dan Gohman475871a2008-07-27 21:46:04 +00004570 return SDValue();
Nate Begeman452d7be2005-09-16 00:54:12 +00004571}
4572
Bill Wendlingf62b2742013-11-22 05:18:07 +00004573static
4574std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4575 SDLoc DL(N);
4576 EVT LoVT, HiVT;
Stephen Hines36b56882014-04-23 16:57:46 -07004577 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Bill Wendlingf62b2742013-11-22 05:18:07 +00004578
4579 // Split the inputs.
4580 SDValue Lo, Hi, LL, LH, RL, RH;
Stephen Hines36b56882014-04-23 16:57:46 -07004581 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4582 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Bill Wendlingf62b2742013-11-22 05:18:07 +00004583
4584 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4585 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4586
4587 return std::make_pair(Lo, Hi);
4588}
4589
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004590SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 SDValue N1 = N->getOperand(1);
4593 SDValue N2 = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004594 SDLoc DL(N);
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004595
4596 // Canonicalize integer abs.
4597 // vselect (setg[te] X, 0), X, -X ->
4598 // vselect (setgt X, -1), X, -X ->
4599 // vselect (setl[te] X, 0), -X, X ->
4600 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4601 if (N0.getOpcode() == ISD::SETCC) {
4602 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4603 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4604 bool isAbs = false;
4605 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4606
4607 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4608 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4609 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4610 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4611 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4612 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4613 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4614
4615 if (isAbs) {
4616 EVT VT = LHS.getValueType();
4617 SDValue Shift = DAG.getNode(
4618 ISD::SRA, DL, VT, LHS,
4619 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4620 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4621 AddToWorkList(Shift.getNode());
4622 AddToWorkList(Add.getNode());
4623 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4624 }
4625 }
4626
Bill Wendlingf62b2742013-11-22 05:18:07 +00004627 // If the VSELECT result requires splitting and the mask is provided by a
4628 // SETCC, then split both nodes and its operands before legalization. This
4629 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4630 // and enables future optimizations (e.g. min/max pattern matching on X86).
4631 if (N0.getOpcode() == ISD::SETCC) {
4632 EVT VT = N->getValueType(0);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004633
Bill Wendlingf62b2742013-11-22 05:18:07 +00004634 // Check if any splitting is required.
4635 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4636 TargetLowering::TypeSplitVector)
4637 return SDValue();
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004638
Bill Wendlingf62b2742013-11-22 05:18:07 +00004639 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Stephen Hines36b56882014-04-23 16:57:46 -07004640 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4641 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4642 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004643
Bill Wendlingf62b2742013-11-22 05:18:07 +00004644 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4645 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004646
Bill Wendlingf62b2742013-11-22 05:18:07 +00004647 // Add the new VSELECT nodes to the work list in case they need to be split
4648 // again.
4649 AddToWorkList(Lo.getNode());
4650 AddToWorkList(Hi.getNode());
4651
4652 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzkac7e77f92013-11-13 01:57:54 +00004653 }
4654
Stephen Hines36b56882014-04-23 16:57:46 -07004655 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4656 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4657 return N1;
4658 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4659 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4660 return N2;
4661
Benjamin Kramer6242fda2013-04-26 09:19:19 +00004662 return SDValue();
4663}
4664
Dan Gohman475871a2008-07-27 21:46:04 +00004665SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4666 SDValue N0 = N->getOperand(0);
4667 SDValue N1 = N->getOperand(1);
4668 SDValue N2 = N->getOperand(2);
4669 SDValue N3 = N->getOperand(3);
4670 SDValue N4 = N->getOperand(4);
Nate Begeman44728a72005-09-19 22:34:01 +00004671 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelfdc40a02009-02-17 22:15:04 +00004672
Nate Begeman44728a72005-09-19 22:34:01 +00004673 // fold select_cc lhs, rhs, x, x, cc -> x
4674 if (N2 == N3)
4675 return N2;
Scott Michelfdc40a02009-02-17 22:15:04 +00004676
Chris Lattner5f42a242006-09-20 06:19:26 +00004677 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +00004678 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004679 N0, N1, CC, SDLoc(N), false);
Stephen Lin7e6d6202013-06-15 04:03:33 +00004680 if (SCC.getNode()) {
4681 AddToWorkList(SCC.getNode());
Chris Lattner5f42a242006-09-20 06:19:26 +00004682
Stephen Lin7e6d6202013-06-15 04:03:33 +00004683 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4684 if (!SCCC->isNullValue())
4685 return N2; // cond always true -> true val
4686 else
4687 return N3; // cond always false -> false val
4688 }
4689
4690 // Fold to a simpler select_cc
4691 if (SCC.getOpcode() == ISD::SETCC)
4692 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4693 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4694 SCC.getOperand(2));
Chris Lattner5f42a242006-09-20 06:19:26 +00004695 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004696
Chris Lattner40c62d52005-10-18 06:04:22 +00004697 // If we can fold this based on the true/false value, do so.
4698 if (SimplifySelectOps(N, N2, N3))
Dan Gohman475871a2008-07-27 21:46:04 +00004699 return SDValue(N, 0); // Don't revisit N.
Scott Michelfdc40a02009-02-17 22:15:04 +00004700
Nate Begeman44728a72005-09-19 22:34:01 +00004701 // fold select_cc into other things, such as min/max/abs
Andrew Trickac6d9be2013-05-25 02:42:55 +00004702 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman452d7be2005-09-16 00:54:12 +00004703}
4704
Dan Gohman475871a2008-07-27 21:46:04 +00004705SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman452d7be2005-09-16 00:54:12 +00004706 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00004707 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004708 SDLoc(N));
Nate Begeman452d7be2005-09-16 00:54:12 +00004709}
4710
Stephen Hines36b56882014-04-23 16:57:46 -07004711// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4712// dag node into a ConstantSDNode or a build_vector of constants.
4713// This function is called by the DAGCombiner when visiting sext/zext/aext
Stephen Hinesdce4a402014-05-29 02:49:00 -07004714// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Stephen Hines36b56882014-04-23 16:57:46 -07004715// Vector extends are not folded if operations are legal; this is to
4716// avoid introducing illegal build_vector dag nodes.
4717static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4718 SelectionDAG &DAG, bool LegalTypes,
4719 bool LegalOperations) {
4720 unsigned Opcode = N->getOpcode();
4721 SDValue N0 = N->getOperand(0);
4722 EVT VT = N->getValueType(0);
4723
4724 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4725 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4726
4727 // fold (sext c1) -> c1
4728 // fold (zext c1) -> c1
4729 // fold (aext c1) -> c1
4730 if (isa<ConstantSDNode>(N0))
4731 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4732
4733 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4734 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4735 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4736 EVT SVT = VT.getScalarType();
4737 if (!(VT.isVector() &&
4738 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4739 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Stephen Hinesdce4a402014-05-29 02:49:00 -07004740 return nullptr;
4741
Stephen Hines36b56882014-04-23 16:57:46 -07004742 // We can fold this node into a build_vector.
4743 unsigned VTBits = SVT.getSizeInBits();
4744 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4745 unsigned ShAmt = VTBits - EVTBits;
4746 SmallVector<SDValue, 8> Elts;
4747 unsigned NumElts = N0->getNumOperands();
4748 SDLoc DL(N);
4749
4750 for (unsigned i=0; i != NumElts; ++i) {
4751 SDValue Op = N0->getOperand(i);
4752 if (Op->getOpcode() == ISD::UNDEF) {
4753 Elts.push_back(DAG.getUNDEF(SVT));
4754 continue;
4755 }
4756
4757 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4758 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4759 if (Opcode == ISD::SIGN_EXTEND)
4760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4761 SVT));
4762 else
4763 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4764 SVT));
4765 }
4766
Stephen Hinesdce4a402014-05-29 02:49:00 -07004767 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Stephen Hines36b56882014-04-23 16:57:46 -07004768}
4769
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004770// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman57fc82d2009-04-09 03:51:29 +00004771// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004772// transformation. Returns true if extension are possible and the above
Scott Michelfdc40a02009-02-17 22:15:04 +00004773// mentioned transformation is profitable.
Dan Gohman475871a2008-07-27 21:46:04 +00004774static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004775 unsigned ExtOpc,
Craig Toppera0ec3f92013-07-14 04:42:23 +00004776 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman79ce2762009-01-15 19:20:50 +00004777 const TargetLowering &TLI) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004778 bool HasCopyToRegUses = false;
4779 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greif12632d22008-08-30 19:29:20 +00004780 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4781 UE = N0.getNode()->use_end();
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004782 UI != UE; ++UI) {
Dan Gohman89684502008-07-27 20:43:25 +00004783 SDNode *User = *UI;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004784 if (User == N)
4785 continue;
Dan Gohman57fc82d2009-04-09 03:51:29 +00004786 if (UI.getUse().getResNo() != N0.getResNo())
4787 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004788 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman57fc82d2009-04-09 03:51:29 +00004789 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004790 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4791 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4792 // Sign bits will be lost after a zext.
4793 return false;
4794 bool Add = false;
4795 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00004796 SDValue UseOp = User->getOperand(i);
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004797 if (UseOp == N0)
4798 continue;
4799 if (!isa<ConstantSDNode>(UseOp))
4800 return false;
4801 Add = true;
4802 }
4803 if (Add)
4804 ExtendNodes.push_back(User);
Dan Gohman57fc82d2009-04-09 03:51:29 +00004805 continue;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004806 }
Dan Gohman57fc82d2009-04-09 03:51:29 +00004807 // If truncates aren't free and there are users we can't
4808 // extend, it isn't worthwhile.
4809 if (!isTruncFree)
4810 return false;
4811 // Remember if this value is live-out.
4812 if (User->getOpcode() == ISD::CopyToReg)
4813 HasCopyToRegUses = true;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004814 }
4815
4816 if (HasCopyToRegUses) {
4817 bool BothLiveOut = false;
4818 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4819 UI != UE; ++UI) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00004820 SDUse &Use = UI.getUse();
4821 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4822 BothLiveOut = true;
4823 break;
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004824 }
4825 }
4826 if (BothLiveOut)
4827 // Both unextended and extended values are live out. There had better be
Bob Wilsonbebfbc52010-11-28 06:51:19 +00004828 // a good reason for the transformation.
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004829 return ExtendNodes.size();
4830 }
4831 return true;
4832}
4833
Craig Topper6c64fba2013-07-13 07:43:40 +00004834void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004835 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004836 ISD::NodeType ExtType) {
4837 // Extend SetCC uses if necessary.
4838 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4839 SDNode *SetCC = SetCCs[i];
4840 SmallVector<SDValue, 4> Ops;
4841
4842 for (unsigned j = 0; j != 2; ++j) {
4843 SDValue SOp = SetCC->getOperand(j);
4844 if (SOp == Trunc)
4845 Ops.push_back(ExtLoad);
4846 else
4847 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4848 }
4849
4850 Ops.push_back(SetCC->getOperand(2));
Stephen Hinesdce4a402014-05-29 02:49:00 -07004851 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004852 }
4853}
4854
Dan Gohman475871a2008-07-27 21:46:04 +00004855SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4856 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00004857 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00004858
Stephen Hines36b56882014-04-23 16:57:46 -07004859 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4860 LegalOperations))
4861 return SDValue(Res, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00004862
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004863 // fold (sext (sext x)) -> (sext x)
4864 // fold (sext (aext x)) -> (sext x)
4865 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004866 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem0c8607b2013-01-20 08:35:56 +00004867 N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00004868
Chris Lattner22558872007-02-26 03:13:59 +00004869 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004870 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4871 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004872 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4873 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00004874 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4875 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004876 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00004877 // CombineTo deleted the truncate, if needed, but not what's under it.
4878 AddToWorkList(oye);
4879 }
Dan Gohmanc7b34442009-04-27 02:00:55 +00004880 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00004881 }
Evan Chengc88138f2007-03-22 01:54:19 +00004882
Dan Gohman1fdfa6a2008-05-20 20:56:33 +00004883 // See if the value being truncated is already sign extended. If so, just
4884 // eliminate the trunc/sext pair.
Dan Gohman475871a2008-07-27 21:46:04 +00004885 SDValue Op = N0.getOperand(0);
Dan Gohmand1996362010-01-09 02:13:55 +00004886 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4887 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4888 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohmanea859be2007-06-22 14:59:07 +00004889 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelfdc40a02009-02-17 22:15:04 +00004890
Chris Lattner22558872007-02-26 03:13:59 +00004891 if (OpBits == DestBits) {
4892 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4893 // bits, it is already ready.
4894 if (NumSignBits > DestBits-MidBits)
4895 return Op;
4896 } else if (OpBits < DestBits) {
4897 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4898 // bits, just sext from i32.
4899 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004900 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattner22558872007-02-26 03:13:59 +00004901 } else {
4902 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4903 // bits, just truncate to i32.
4904 if (NumSignBits > OpBits-MidBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004905 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattner6007b842006-09-21 06:00:20 +00004906 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004907
Chris Lattner22558872007-02-26 03:13:59 +00004908 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sands25cf2272008-11-24 14:53:14 +00004909 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4910 N0.getValueType())) {
Dan Gohmand1996362010-01-09 02:13:55 +00004911 if (OpBits < DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004912 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohmand1996362010-01-09 02:13:55 +00004913 else if (OpBits > DestBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00004914 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohmand1996362010-01-09 02:13:55 +00004916 DAG.getValueType(N0.getValueType()));
Chris Lattner22558872007-02-26 03:13:59 +00004917 }
Chris Lattner6007b842006-09-21 06:00:20 +00004918 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004919
Evan Cheng110dec22005-12-14 02:19:23 +00004920 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004921 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemfcd96192011-02-27 07:40:43 +00004922 // on vectors in one instruction. We only perform this transformation on
4923 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00004924 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Stephen Hinesdce4a402014-05-29 02:49:00 -07004925 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00004926 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00004927 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004928 bool DoXform = true;
4929 SmallVector<SDNode*, 4> SetCCs;
4930 if (!N0.hasOneUse())
4931 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4932 if (DoXform) {
4933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00004935 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004936 LN0->getBasePtr(), N0.getValueType(),
4937 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004938 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004939 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004940 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00004941 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004942 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004943 ISD::SIGN_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00004944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00004945 }
Nate Begeman3df4d522005-10-12 20:40:40 +00004946 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004947
4948 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4949 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00004950 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4951 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00004952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00004953 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00004954 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00004955 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004956 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00004957 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004958 LN0->getBasePtr(), MemVT,
4959 LN0->getMemOperand());
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004960 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00004961 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004962 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00004963 N0.getValueType(), ExtLoad),
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004964 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00004965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskeyf6c4ccf2006-12-15 21:38:30 +00004966 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00004967 }
Scott Michelfdc40a02009-02-17 22:15:04 +00004968
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004969 // fold (sext (and/or/xor (load x), cst)) ->
4970 // (and/or/xor (sextload x), (sext cst))
4971 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4972 N0.getOpcode() == ISD::XOR) &&
4973 isa<LoadSDNode>(N0.getOperand(0)) &&
4974 N0.getOperand(1).getOpcode() == ISD::Constant &&
4975 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4976 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4977 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Stephen Hinesdce4a402014-05-29 02:49:00 -07004978 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004979 bool DoXform = true;
4980 SmallVector<SDNode*, 4> SetCCs;
4981 if (!N0.hasOneUse())
4982 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4983 SetCCs, TLI);
4984 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004986 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004987 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00004988 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004989 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4990 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004991 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004992 ExtLoad, DAG.getConstant(Mask, VT));
4993 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00004994 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004995 N0.getOperand(0).getValueType(), ExtLoad);
4996 CombineTo(N, And);
4997 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004998 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00004999 ISD::SIGN_EXTEND);
5000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5001 }
5002 }
5003 }
5004
Chris Lattner20a35c32007-04-11 05:32:27 +00005005 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner2b7a2712009-07-08 00:31:33 +00005006 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohman3ce89f42010-04-30 17:19:19 +00005007 // Only do this before legalize for now.
Owen Andersoned5707b2013-04-23 18:09:28 +00005008 if (VT.isVector() && !LegalOperations &&
Stephen Lin155615d2013-07-08 00:37:03 +00005009 TLI.getBooleanContents(true) ==
Owen Andersoned5707b2013-04-23 18:09:28 +00005010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohman3ce89f42010-04-30 17:19:19 +00005011 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem2e506192012-04-11 08:26:11 +00005012 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5013 // of the same size as the compared operands. Only optimize sext(setcc())
5014 // if this is the case.
Matt Arsenault225ed702013-05-18 00:21:46 +00005015 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem2e506192012-04-11 08:26:11 +00005016
5017 // We know that the # elements of the results is the same as the
5018 // # elements of the compare (and the # elements of the compare result
5019 // for that matter). Check to see that they are the same size. If so,
5020 // we know that the element size of the sext'd result matches the
5021 // element size of the compare operands.
5022 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005023 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005024 N0.getOperand(1),
5025 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00005026
Dan Gohman3ce89f42010-04-30 17:19:19 +00005027 // If the desired elements are smaller or larger than the source
5028 // elements we can use a matching integer vector type and then
5029 // truncate/sign extend
Matt Arsenault9aa8fdf2013-05-17 21:43:43 +00005030 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper0eb5dad2012-09-29 07:18:53 +00005031 if (SVT == MatchingVectorType) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005032 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper0eb5dad2012-09-29 07:18:53 +00005033 N0.getOperand(0), N0.getOperand(1),
5034 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005035 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohman3ce89f42010-04-30 17:19:19 +00005036 }
Chris Lattner2b7a2712009-07-08 00:31:33 +00005037 }
Dan Gohman3ce89f42010-04-30 17:19:19 +00005038
Stephen Hines36b56882014-04-23 16:57:46 -07005039 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohmana7bcef12010-04-24 01:17:30 +00005040 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5cbd37e2009-08-06 09:18:59 +00005041 SDValue NegOne =
Dan Gohmana7bcef12010-04-24 01:17:30 +00005042 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelfdc40a02009-02-17 22:15:04 +00005043 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005044 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5cbd37e2009-08-06 09:18:59 +00005045 NegOne, DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005046 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005047 if (SCC.getNode()) return SCC;
Stephen Hines36b56882014-04-23 16:57:46 -07005048
5049 if (!VT.isVector()) {
5050 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5051 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5052 SDLoc DL(N);
5053 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5054 SDValue SetCC = DAG.getSetCC(DL,
5055 SetCCVT,
5056 N0.getOperand(0), N0.getOperand(1), CC);
5057 EVT SelectVT = getSetCCResultType(VT);
5058 return DAG.getSelect(DL, VT,
5059 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5060 NegOne, DAG.getConstant(0, VT));
5061
5062 }
Matt Arsenaultb05e4772013-06-14 22:04:37 +00005063 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005064 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005065
Dan Gohman8f0ad582008-04-28 16:58:24 +00005066 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sands25cf2272008-11-24 14:53:14 +00005067 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohman187db7b2008-04-28 18:47:17 +00005068 DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005069 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005070
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005071 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005072}
5073
Rafael Espindoladecbc432012-04-09 16:06:03 +00005074// isTruncateOf - If N is a truncate of some other value, return true, record
5075// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5076// This function computes KnownZero to avoid a duplicated call to
Stephen Hinesdce4a402014-05-29 02:49:00 -07005077// computeKnownBits in the caller.
Rafael Espindoladecbc432012-04-09 16:06:03 +00005078static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5079 APInt &KnownZero) {
5080 APInt KnownOne;
5081 if (N->getOpcode() == ISD::TRUNCATE) {
5082 Op = N->getOperand(0);
Stephen Hinesdce4a402014-05-29 02:49:00 -07005083 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindoladecbc432012-04-09 16:06:03 +00005084 return true;
5085 }
5086
5087 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5088 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5089 return false;
5090
5091 SDValue Op0 = N->getOperand(0);
5092 SDValue Op1 = N->getOperand(1);
5093 assert(Op0.getValueType() == Op1.getValueType());
5094
5095 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5096 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindolafdb230a2012-04-10 00:16:22 +00005097 if (COp0 && COp0->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00005098 Op = Op1;
Rafael Espindolafdb230a2012-04-10 00:16:22 +00005099 else if (COp1 && COp1->isNullValue())
Rafael Espindoladecbc432012-04-09 16:06:03 +00005100 Op = Op0;
5101 else
5102 return false;
5103
Stephen Hinesdce4a402014-05-29 02:49:00 -07005104 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindoladecbc432012-04-09 16:06:03 +00005105
5106 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5107 return false;
5108
5109 return true;
5110}
5111
Dan Gohman475871a2008-07-27 21:46:04 +00005112SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5113 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005114 EVT VT = N->getValueType(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005115
Stephen Hines36b56882014-04-23 16:57:46 -07005116 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5117 LegalOperations))
5118 return SDValue(Res, 0);
5119
Nate Begeman1d4d4142005-09-01 00:19:25 +00005120 // fold (zext (zext x)) -> (zext x)
Chris Lattner310b5782006-05-06 23:06:26 +00005121 // fold (zext (aext x)) -> (zext x)
5122 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005123 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005124 N0.getOperand(0));
Chris Lattner6007b842006-09-21 06:00:20 +00005125
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005126 // fold (zext (truncate x)) -> (zext x) or
5127 // (zext (truncate x)) -> (truncate x)
5128 // This is valid when the truncated bits of x are already zero.
5129 // FIXME: We should extend this to work for vectors too.
Rafael Espindoladecbc432012-04-09 16:06:03 +00005130 SDValue Op;
5131 APInt KnownZero;
5132 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5133 APInt TruncatedBits =
5134 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5135 APInt(Op.getValueSizeInBits(), 0) :
5136 APInt::getBitsSet(Op.getValueSizeInBits(),
5137 N0.getValueSizeInBits(),
5138 std::min(Op.getValueSizeInBits(),
5139 VT.getSizeInBits()));
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00005140 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005141 if (VT.bitsGT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005143 if (VT.bitsLT(Op.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruthf103b3d2012-01-11 08:41:08 +00005145
5146 return Op;
5147 }
5148 }
5149
Evan Chengc88138f2007-03-22 01:54:19 +00005150 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5151 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen2041a0e2007-03-30 21:38:07 +00005152 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005153 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5154 if (NarrowLoad.getNode()) {
Dale Johannesen61734eb2010-05-25 17:50:03 +00005155 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5156 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005157 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen61734eb2010-05-25 17:50:03 +00005158 // CombineTo deleted the truncate, if needed, but not what's under it.
5159 AddToWorkList(oye);
5160 }
Eli Friedmane545d382011-04-16 23:25:34 +00005161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00005162 }
Evan Chengc88138f2007-03-22 01:54:19 +00005163 }
5164
Chris Lattner6007b842006-09-21 06:00:20 +00005165 // fold (zext (truncate x)) -> (and x, mask)
5166 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005167 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman394d6292010-11-03 01:47:46 +00005168
5169 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5170 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5171 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5172 if (NarrowLoad.getNode()) {
5173 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5174 if (NarrowLoad.getNode() != N0.getNode()) {
5175 CombineTo(N0.getNode(), NarrowLoad);
5176 // CombineTo deleted the truncate, if needed, but not what's under it.
5177 AddToWorkList(oye);
5178 }
5179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5180 }
5181
Dan Gohman475871a2008-07-27 21:46:04 +00005182 SDValue Op = N0.getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005183 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005184 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00005185 AddToWorkList(Op.getNode());
Duncan Sands8e4eb092008-06-08 20:54:56 +00005186 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005187 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky1da58672012-04-22 09:39:03 +00005188 AddToWorkList(Op.getNode());
Chris Lattner6007b842006-09-21 06:00:20 +00005189 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00005190 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman87862e72009-12-11 21:31:27 +00005191 N0.getValueType().getScalarType());
Chris Lattner6007b842006-09-21 06:00:20 +00005192 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005193
Dan Gohman97121ba2009-04-08 00:15:30 +00005194 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5195 // if either of the casts is not free.
Chris Lattner111c2282006-09-21 06:14:31 +00005196 if (N0.getOpcode() == ISD::AND &&
5197 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00005198 N0.getOperand(1).getOpcode() == ISD::Constant &&
5199 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5200 N0.getValueType()) ||
5201 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman475871a2008-07-27 21:46:04 +00005202 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005203 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005204 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005205 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner111c2282006-09-21 06:14:31 +00005207 }
Dan Gohman220a8232008-03-03 23:51:38 +00005208 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00005209 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005211 X, DAG.getConstant(Mask, VT));
Chris Lattner111c2282006-09-21 06:14:31 +00005212 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005213
Evan Cheng110dec22005-12-14 02:19:23 +00005214 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotemed9b9342011-02-20 12:37:50 +00005215 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemfcd96192011-02-27 07:40:43 +00005216 // on vectors in one instruction. We only perform this transformation on
5217 // scalars.
Nadav Rotemed9b9342011-02-20 12:37:50 +00005218 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Stephen Hinesdce4a402014-05-29 02:49:00 -07005219 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005220 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005221 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005222 bool DoXform = true;
5223 SmallVector<SDNode*, 4> SetCCs;
5224 if (!N0.hasOneUse())
5225 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5226 if (DoXform) {
5227 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005228 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005229 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005230 LN0->getBasePtr(), N0.getValueType(),
5231 LN0->getMemOperand());
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005232 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005233 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling6ce610f2009-01-30 22:23:15 +00005234 N0.getValueType(), ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005235 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendling6ce610f2009-01-30 22:23:15 +00005236
Andrew Trickac6d9be2013-05-25 02:42:55 +00005237 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005238 ISD::ZERO_EXTEND);
Dan Gohman475871a2008-07-27 21:46:04 +00005239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng3c3ddb32007-10-29 19:58:20 +00005240 }
Evan Cheng110dec22005-12-14 02:19:23 +00005241 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005242
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005243 // fold (zext (and/or/xor (load x), cst)) ->
5244 // (and/or/xor (zextload x), (zext cst))
5245 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5246 N0.getOpcode() == ISD::XOR) &&
5247 isa<LoadSDNode>(N0.getOperand(0)) &&
5248 N0.getOperand(1).getOpcode() == ISD::Constant &&
5249 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5250 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5251 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Stephen Hinesdce4a402014-05-29 02:49:00 -07005252 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005253 bool DoXform = true;
5254 SmallVector<SDNode*, 4> SetCCs;
5255 if (!N0.hasOneUse())
5256 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5257 SetCCs, TLI);
5258 if (DoXform) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005259 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005260 LN0->getChain(), LN0->getBasePtr(),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005261 LN0->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005262 LN0->getMemOperand());
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005263 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5264 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005265 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005266 ExtLoad, DAG.getConstant(Mask, VT));
5267 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005268 SDLoc(N0.getOperand(0)),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005269 N0.getOperand(0).getValueType(), ExtLoad);
5270 CombineTo(N, And);
5271 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005272 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005273 ISD::ZERO_EXTEND);
5274 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5275 }
5276 }
5277 }
5278
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005279 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5280 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greifba36cb52008-08-28 21:40:38 +00005281 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5282 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Cheng466685d2006-10-09 20:57:25 +00005283 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman8a55ce42009-09-23 21:02:20 +00005284 EVT MemVT = LN0->getMemoryVT();
Duncan Sands25cf2272008-11-24 14:53:14 +00005285 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman8a55ce42009-09-23 21:02:20 +00005286 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005287 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendling6ce610f2009-01-30 22:23:15 +00005288 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005289 LN0->getBasePtr(), MemVT,
5290 LN0->getMemOperand());
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005291 CombineTo(N, ExtLoad);
Gabor Greif12632d22008-08-30 19:29:20 +00005292 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005293 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendling6ce610f2009-01-30 22:23:15 +00005294 ExtLoad),
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005295 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sandsd4b9c172008-06-13 19:07:40 +00005297 }
Chris Lattnerad25d4e2005-12-14 19:05:06 +00005298 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005299
Chris Lattner20a35c32007-04-11 05:32:27 +00005300 if (N0.getOpcode() == ISD::SETCC) {
Stephen Hines36b56882014-04-23 16:57:46 -07005301 if (!LegalOperations && VT.isVector() &&
5302 N0.getValueType().getVectorElementType() == MVT::i1) {
5303 EVT N0VT = N0.getOperand(0).getValueType();
5304 if (getSetCCResultType(N0VT) == N0.getValueType())
5305 return SDValue();
5306
Evan Cheng0a942db2010-05-19 01:08:17 +00005307 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5308 // Only do this before legalize for now.
Evan Cheng0a942db2010-05-19 01:08:17 +00005309 EVT EltVT = VT.getVectorElementType();
5310 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5311 DAG.getConstant(1, EltVT));
Dan Gohman71dc7c92011-05-17 22:20:36 +00005312 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Cheng0a942db2010-05-19 01:08:17 +00005313 // We know that the # elements of the results is the same as the
5314 // # elements of the compare (and the # elements of the compare result
5315 // for that matter). Check to see that they are the same size. If so,
5316 // we know that the element size of the sext'd result matches the
5317 // element size of the compare operands.
Andrew Trickac6d9be2013-05-25 02:42:55 +00005318 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5319 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Cheng0a942db2010-05-19 01:08:17 +00005320 N0.getOperand(1),
5321 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005322 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Stephen Hinesdce4a402014-05-29 02:49:00 -07005323 OneOps));
Dan Gohman71dc7c92011-05-17 22:20:36 +00005324
5325 // If the desired elements are smaller or larger than the source
5326 // elements we can use a matching integer vector type and then
5327 // truncate/sign extend
5328 EVT MatchingElementType =
5329 EVT::getIntegerVT(*DAG.getContext(),
5330 N0VT.getScalarType().getSizeInBits());
5331 EVT MatchingVectorType =
5332 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5333 N0VT.getVectorNumElements());
5334 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005335 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman71dc7c92011-05-17 22:20:36 +00005336 N0.getOperand(1),
5337 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005338 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5339 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Stephen Hinesdce4a402014-05-29 02:49:00 -07005340 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Cheng0a942db2010-05-19 01:08:17 +00005341 }
5342
5343 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005344 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005345 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner20a35c32007-04-11 05:32:27 +00005346 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005348 if (SCC.getNode()) return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005349 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005350
Evan Cheng9818c042009-12-15 03:00:32 +00005351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Cheng99b653c2009-12-15 00:41:36 +00005352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng9818c042009-12-15 03:00:32 +00005353 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Cheng99b653c2009-12-15 00:41:36 +00005354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5355 N0.hasOneUse()) {
Chris Lattnere0751182011-02-13 19:09:16 +00005356 SDValue ShAmt = N0.getOperand(1);
5357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng9818c042009-12-15 03:00:32 +00005358 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere0751182011-02-13 19:09:16 +00005359 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng9818c042009-12-15 03:00:32 +00005360 // If the original shl may be shifting out bits, do not perform this
5361 // transformation.
Chris Lattnere0751182011-02-13 19:09:16 +00005362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364 if (ShAmtVal > KnownZeroBits)
Evan Cheng9818c042009-12-15 03:00:32 +00005365 return SDValue();
5366 }
Chris Lattnere0751182011-02-13 19:09:16 +00005367
Andrew Trickac6d9be2013-05-25 02:42:55 +00005368 SDLoc DL(N);
Owen Anderson95771af2011-02-25 21:41:48 +00005369
5370 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere0751182011-02-13 19:09:16 +00005371 if (VT.getSizeInBits() >= 256)
5372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Anderson95771af2011-02-25 21:41:48 +00005373
Chris Lattnere0751182011-02-13 19:09:16 +00005374 return DAG.getNode(N0.getOpcode(), DL, VT,
5375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5376 ShAmt);
Evan Cheng99b653c2009-12-15 00:41:36 +00005377 }
5378
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005379 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005380}
5381
Dan Gohman475871a2008-07-27 21:46:04 +00005382SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005384 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005385
Stephen Hines36b56882014-04-23 16:57:46 -07005386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5387 LegalOperations))
5388 return SDValue(Res, 0);
5389
Chris Lattner5ffc0662006-05-05 05:58:59 +00005390 // fold (aext (aext x)) -> (aext x)
5391 // fold (aext (zext x)) -> (zext x)
5392 // fold (aext (sext x)) -> (sext x)
5393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5394 N0.getOpcode() == ISD::ZERO_EXTEND ||
5395 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00005397
Evan Chengc88138f2007-03-22 01:54:19 +00005398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005401 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402 if (NarrowLoad.getNode()) {
Dale Johannesen86234c32010-05-25 18:47:23 +00005403 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005405 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen86234c32010-05-25 18:47:23 +00005406 // CombineTo deleted the truncate, if needed, but not what's under it.
5407 AddToWorkList(oye);
5408 }
Eli Friedmane545d382011-04-16 23:25:34 +00005409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng0b063de2007-03-23 02:16:52 +00005410 }
Evan Chengc88138f2007-03-22 01:54:19 +00005411 }
5412
Chris Lattner84750582006-09-20 06:29:17 +00005413 // fold (aext (truncate x))
5414 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman475871a2008-07-27 21:46:04 +00005415 SDValue TruncOp = N0.getOperand(0);
Chris Lattner84750582006-09-20 06:29:17 +00005416 if (TruncOp.getValueType() == VT)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005417 return TruncOp; // x iff x size == zext size.
Duncan Sands8e4eb092008-06-08 20:54:56 +00005418 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner84750582006-09-20 06:29:17 +00005421 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005422
Dan Gohman97121ba2009-04-08 00:15:30 +00005423 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424 // if the trunc is not free.
Chris Lattner0e4b9222006-09-21 06:40:43 +00005425 if (N0.getOpcode() == ISD::AND &&
5426 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohman97121ba2009-04-08 00:15:30 +00005427 N0.getOperand(1).getOpcode() == ISD::Constant &&
5428 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429 N0.getValueType())) {
Dan Gohman475871a2008-07-27 21:46:04 +00005430 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005431 if (X.getValueType().bitsLT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005432 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands8e4eb092008-06-08 20:54:56 +00005433 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005434 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner0e4b9222006-09-21 06:40:43 +00005435 }
Dan Gohman220a8232008-03-03 23:51:38 +00005436 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad40f8f622010-12-07 08:25:19 +00005437 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00005438 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling683c9572009-01-30 22:27:33 +00005439 X, DAG.getConstant(Mask, VT));
Chris Lattner0e4b9222006-09-21 06:40:43 +00005440 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005441
Chris Lattner5ffc0662006-05-05 05:58:59 +00005442 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005443 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemfcd96192011-02-27 07:40:43 +00005444 // on vectors in one instruction. We only perform this transformation on
5445 // scalars.
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Stephen Hinesdce4a402014-05-29 02:49:00 -07005447 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005448 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005449 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman57fc82d2009-04-09 03:51:29 +00005450 bool DoXform = true;
5451 SmallVector<SDNode*, 4> SetCCs;
5452 if (!N0.hasOneUse())
5453 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5454 if (DoXform) {
5455 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005456 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman57fc82d2009-04-09 03:51:29 +00005457 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005458 LN0->getBasePtr(), N0.getValueType(),
5459 LN0->getMemOperand());
Dan Gohman57fc82d2009-04-09 03:51:29 +00005460 CombineTo(N, ExtLoad);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005461 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman57fc82d2009-04-09 03:51:29 +00005462 N0.getValueType(), ExtLoad);
5463 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005464 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewyckyc06b5bf2011-06-16 01:15:49 +00005465 ISD::ANY_EXTEND);
Dan Gohman57fc82d2009-04-09 03:51:29 +00005466 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5467 }
Chris Lattner5ffc0662006-05-05 05:58:59 +00005468 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005469
Chris Lattner5ffc0662006-05-05 05:58:59 +00005470 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5471 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5472 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng83060c52007-03-07 08:07:03 +00005473 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005474 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng466685d2006-10-09 20:57:25 +00005475 N0.hasOneUse()) {
5476 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Stephen Hinesdce4a402014-05-29 02:49:00 -07005477 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman8a55ce42009-09-23 21:02:20 +00005478 EVT MemVT = LN0->getMemoryVT();
Stephen Hinesdce4a402014-05-29 02:49:00 -07005479 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5480 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5481 VT, LN0->getChain(), LN0->getBasePtr(),
5482 MemVT, LN0->getMemOperand());
5483 CombineTo(N, ExtLoad);
5484 CombineTo(N0.getNode(),
5485 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5486 N0.getValueType(), ExtLoad),
5487 ExtLoad.getValue(1));
5488 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5489 }
Chris Lattner5ffc0662006-05-05 05:58:59 +00005490 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005491
Chris Lattner20a35c32007-04-11 05:32:27 +00005492 if (N0.getOpcode() == ISD::SETCC) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07005493 // For vectors:
5494 // aext(setcc) -> vsetcc
5495 // aext(setcc) -> truncate(vsetcc)
5496 // aext(setcc) -> aext(vsetcc)
Evan Cheng0a942db2010-05-19 01:08:17 +00005497 // Only do this before legalize for now.
5498 if (VT.isVector() && !LegalOperations) {
5499 EVT N0VT = N0.getOperand(0).getValueType();
5500 // We know that the # elements of the results is the same as the
5501 // # elements of the compare (and the # elements of the compare result
5502 // for that matter). Check to see that they are the same size. If so,
5503 // we know that the element size of the sext'd result matches the
5504 // element size of the compare operands.
5505 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005506 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005507 N0.getOperand(1),
5508 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Cheng0a942db2010-05-19 01:08:17 +00005509 // If the desired elements are smaller or larger than the source
5510 // elements we can use a matching integer vector type and then
Stephen Hinesdce4a402014-05-29 02:49:00 -07005511 // truncate/any extend
Evan Cheng0a942db2010-05-19 01:08:17 +00005512 else {
Stephen Hinesdce4a402014-05-29 02:49:00 -07005513 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands34727662010-07-12 08:16:59 +00005514 SDValue VsetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005515 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands34727662010-07-12 08:16:59 +00005516 N0.getOperand(1),
5517 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Stephen Hinesdce4a402014-05-29 02:49:00 -07005518 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Cheng0a942db2010-05-19 01:08:17 +00005519 }
5520 }
5521
5522 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelfdc40a02009-02-17 22:15:04 +00005523 SDValue SCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00005524 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner1eba01e2007-04-11 06:50:51 +00005525 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnerc24bbad2007-04-11 16:51:53 +00005526 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greifba36cb52008-08-28 21:40:38 +00005527 if (SCC.getNode())
Chris Lattnerc56a81d2007-04-11 06:43:25 +00005528 return SCC;
Chris Lattner20a35c32007-04-11 05:32:27 +00005529 }
Scott Michelfdc40a02009-02-17 22:15:04 +00005530
Evan Chengb3a3d5e2010-04-28 07:10:39 +00005531 return SDValue();
Chris Lattner5ffc0662006-05-05 05:58:59 +00005532}
5533
Chris Lattner2b4c2792007-10-13 06:35:54 +00005534/// GetDemandedBits - See if the specified operand can be simplified with the
5535/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman475871a2008-07-27 21:46:04 +00005536/// simpler operand, otherwise return a null SDValue.
5537SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00005538 switch (V.getOpcode()) {
5539 default: break;
Lang Hames5207bf22011-11-08 18:56:23 +00005540 case ISD::Constant: {
5541 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Stephen Hinesdce4a402014-05-29 02:49:00 -07005542 assert(CV && "Const value should be ConstSDNode.");
Lang Hames5207bf22011-11-08 18:56:23 +00005543 const APInt &CVal = CV->getAPIntValue();
5544 APInt NewVal = CVal & Mask;
Stephen Linb4940152013-07-09 00:44:49 +00005545 if (NewVal != CVal)
Lang Hames5207bf22011-11-08 18:56:23 +00005546 return DAG.getConstant(NewVal, V.getValueType());
Lang Hames5207bf22011-11-08 18:56:23 +00005547 break;
5548 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005549 case ISD::OR:
5550 case ISD::XOR:
5551 // If the LHS or RHS don't contribute bits to the or, drop them.
5552 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5553 return V.getOperand(1);
5554 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5555 return V.getOperand(0);
5556 break;
Chris Lattnere33544c2007-10-13 06:58:48 +00005557 case ISD::SRL:
5558 // Only look at single-use SRLs.
Gabor Greifba36cb52008-08-28 21:40:38 +00005559 if (!V.getNode()->hasOneUse())
Chris Lattnere33544c2007-10-13 06:58:48 +00005560 break;
5561 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5562 // See if we can recursively simplify the LHS.
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005563 unsigned Amt = RHSC->getZExtValue();
Bill Wendling8509c902009-01-30 22:33:24 +00005564
Dan Gohmancc91d632009-01-03 19:22:06 +00005565 // Watch out for shift count overflow though.
5566 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005567 APInt NewMask = Mask << Amt;
Dan Gohman475871a2008-07-27 21:46:04 +00005568 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling8509c902009-01-30 22:33:24 +00005569 if (SimplifyLHS.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005570 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnere33544c2007-10-13 06:58:48 +00005571 SimplifyLHS, V.getOperand(1));
Chris Lattnere33544c2007-10-13 06:58:48 +00005572 }
Chris Lattner2b4c2792007-10-13 06:35:54 +00005573 }
Dan Gohman475871a2008-07-27 21:46:04 +00005574 return SDValue();
Chris Lattner2b4c2792007-10-13 06:35:54 +00005575}
5576
Evan Chengc88138f2007-03-22 01:54:19 +00005577/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5578/// bits and then truncated to a narrower type and where N is a multiple
5579/// of number of bits of the narrower type, transform it to a narrower load
5580/// from address + N / num of bits of new type. If the result is to be
5581/// extended, also fold the extension to form a extending load.
Dan Gohman475871a2008-07-27 21:46:04 +00005582SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Chengc88138f2007-03-22 01:54:19 +00005583 unsigned Opc = N->getOpcode();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005584
Evan Chengc88138f2007-03-22 01:54:19 +00005585 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman475871a2008-07-27 21:46:04 +00005586 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005587 EVT VT = N->getValueType(0);
5588 EVT ExtVT = VT;
Evan Chengc88138f2007-03-22 01:54:19 +00005589
Dan Gohman7f8613e2008-08-14 20:04:46 +00005590 // This transformation isn't valid for vector loads.
5591 if (VT.isVector())
5592 return SDValue();
5593
Dan Gohmand1996362010-01-09 02:13:55 +00005594 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenge177e302007-03-23 22:13:36 +00005595 // extended to VT.
Evan Chengc88138f2007-03-22 01:54:19 +00005596 if (Opc == ISD::SIGN_EXTEND_INREG) {
5597 ExtType = ISD::SEXTLOAD;
Owen Andersone50ed302009-08-10 22:56:29 +00005598 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005599 } else if (Opc == ISD::SRL) {
Chris Lattner90b03642010-12-21 18:05:22 +00005600 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005601 ExtType = ISD::ZEXTLOAD;
5602 N0 = SDValue(N, 0);
5603 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5604 if (!N01) return SDValue();
5605 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5606 VT.getSizeInBits() - N01->getZExtValue());
Evan Chengc88138f2007-03-22 01:54:19 +00005607 }
Richard Osborne4e3740e2011-01-31 17:41:44 +00005608 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5609 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005610
Owen Andersone50ed302009-08-10 22:56:29 +00005611 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Anderson95771af2011-02-25 21:41:48 +00005612
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005613 // Do not generate loads of non-round integer types since these can
5614 // be expensive (and would be wrong if the type is not byte sized).
5615 if (!ExtVT.isRound())
5616 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005617
Evan Chengc88138f2007-03-22 01:54:19 +00005618 unsigned ShAmt = 0;
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005619 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Chengc88138f2007-03-22 01:54:19 +00005620 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005621 ShAmt = N01->getZExtValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005622 // Is the shift amount a multiple of size of VT?
5623 if ((ShAmt & (EVTBits-1)) == 0) {
5624 N0 = N0.getOperand(0);
Eli Friedmand68eea22009-08-19 08:46:10 +00005625 // Is the load width a multiple of size of VT?
5626 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman475871a2008-07-27 21:46:04 +00005627 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005628 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00005629
Chris Lattnercbf68df2010-12-22 08:02:57 +00005630 // At this point, we must have a load or else we can't do the transform.
5631 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005632
Chandler Carruth1c49fda2012-12-11 00:36:57 +00005633 // Because a SRL must be assumed to *need* to zero-extend the high bits
5634 // (as opposed to anyext the high bits), we can't combine the zextload
5635 // lowering of SRL and an sextload.
5636 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5637 return SDValue();
5638
Chris Lattner2831a192010-10-01 05:36:09 +00005639 // If the shift amount is larger than the input type then we're not
5640 // accessing any of the loaded bytes. If the load was a zextload/extload
5641 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercbf68df2010-12-22 08:02:57 +00005642 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattner2831a192010-10-01 05:36:09 +00005643 return SDValue();
Evan Chengc88138f2007-03-22 01:54:19 +00005644 }
5645 }
5646
Dan Gohman394d6292010-11-03 01:47:46 +00005647 // If the load is shifted left (and the result isn't shifted back right),
5648 // we can fold the truncate through the shift.
5649 unsigned ShLeftAmt = 0;
5650 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner4c32bc22010-12-22 07:36:50 +00005651 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman394d6292010-11-03 01:47:46 +00005652 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5653 ShLeftAmt = N01->getZExtValue();
5654 N0 = N0.getOperand(0);
5655 }
5656 }
Owen Anderson95771af2011-02-25 21:41:48 +00005657
Chris Lattner4c32bc22010-12-22 07:36:50 +00005658 // If we haven't found a load, we can't narrow it. Don't transform one with
5659 // multiple uses, this would require adding a new load.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005660 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5661 return SDValue();
5662
5663 // Don't change the width of a volatile load.
5664 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5665 if (LN0->isVolatile())
Chris Lattner4c32bc22010-12-22 07:36:50 +00005666 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005667
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005668 // Verify that we are actually reducing a load width here.
Bill Schmidt89e88e32013-01-14 22:04:38 +00005669 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner4c32bc22010-12-22 07:36:50 +00005670 return SDValue();
Owen Anderson95771af2011-02-25 21:41:48 +00005671
Bill Schmidt89e88e32013-01-14 22:04:38 +00005672 // For the transform to be legal, the load must produce only two values
5673 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lin155615d2013-07-08 00:37:03 +00005674 // load, for example, which produces an extra value. Otherwise the
Bill Schmidt89e88e32013-01-14 22:04:38 +00005675 // transformation is not equivalent, and the downstream logic to replace
5676 // uses gets things wrong.
5677 if (LN0->getNumValues() > 2)
5678 return SDValue();
5679
Benjamin Kramerf4eeab42013-07-06 14:05:09 +00005680 // If the load that we're shrinking is an extload and we're not just
5681 // discarding the extension we can't simply shrink the load. Bail.
5682 // TODO: It would be possible to merge the extensions in some cases.
5683 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5684 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5685 return SDValue();
5686
Chris Lattner4c32bc22010-12-22 07:36:50 +00005687 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling8509c902009-01-30 22:33:24 +00005688
Evan Cheng16436df2012-06-26 01:19:33 +00005689 if (PtrType == MVT::Untyped || PtrType.isExtended())
5690 // It's not possible to generate a constant of extended or untyped type.
5691 return SDValue();
5692
Chris Lattner4c32bc22010-12-22 07:36:50 +00005693 // For big endian targets, we need to adjust the offset to the pointer to
5694 // load the correct bytes.
5695 if (TLI.isBigEndian()) {
5696 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5697 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5698 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Chengc88138f2007-03-22 01:54:19 +00005699 }
5700
Chris Lattner4c32bc22010-12-22 07:36:50 +00005701 uint64_t PtrOff = ShAmt / 8;
5702 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005703 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner4c32bc22010-12-22 07:36:50 +00005704 PtrType, LN0->getBasePtr(),
5705 DAG.getConstant(PtrOff, PtrType));
5706 AddToWorkList(NewPtr.getNode());
5707
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005708 SDValue Load;
5709 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005710 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005711 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005712 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005713 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005714 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005715 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner7a2a7fa2010-12-22 08:01:44 +00005716 LN0->getPointerInfo().getWithOffset(PtrOff),
5717 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005718 NewAlign, LN0->getTBAAInfo());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005719
5720 // Replace the old load's chain with the new load's chain.
5721 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00005722 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005723
5724 // Shift the result left, if we've swallowed a left shift.
5725 SDValue Result = Load;
5726 if (ShLeftAmt != 0) {
Owen Anderson95771af2011-02-25 21:41:48 +00005727 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner4c32bc22010-12-22 07:36:50 +00005728 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5729 ShImmTy = VT;
Paul Redmond5c974502013-02-12 15:21:21 +00005730 // If the shift amount is as large as the result size (but, presumably,
5731 // no larger than the source) then the useful bits of the result are
5732 // zero; we can't simply return the shortened shift, because the result
5733 // of that operation is undefined.
5734 if (ShLeftAmt >= VT.getSizeInBits())
5735 Result = DAG.getConstant(0, VT);
5736 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00005737 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond5c974502013-02-12 15:21:21 +00005738 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner4c32bc22010-12-22 07:36:50 +00005739 }
5740
5741 // Return the new loaded value.
5742 return Result;
Evan Chengc88138f2007-03-22 01:54:19 +00005743}
5744
Dan Gohman475871a2008-07-27 21:46:04 +00005745SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5746 SDValue N0 = N->getOperand(0);
5747 SDValue N1 = N->getOperand(1);
Owen Andersone50ed302009-08-10 22:56:29 +00005748 EVT VT = N->getValueType(0);
5749 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman87862e72009-12-11 21:31:27 +00005750 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohmand1996362010-01-09 02:13:55 +00005751 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00005752
Nate Begeman1d4d4142005-09-01 00:19:25 +00005753 // fold (sext_in_reg c1) -> c1
Chris Lattnereaeda562006-05-08 20:59:41 +00005754 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005755 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00005756
Chris Lattner541a24f2006-05-06 22:43:44 +00005757 // If the input is already sign extended, just drop the extension.
Dan Gohman87862e72009-12-11 21:31:27 +00005758 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattneree4ea922006-05-06 09:30:03 +00005759 return N0;
Scott Michelfdc40a02009-02-17 22:15:04 +00005760
Nate Begeman646d7e22005-09-02 21:18:40 +00005761 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5762 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Linb4940152013-07-09 00:44:49 +00005763 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005764 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005765 N0.getOperand(0), N1);
Chris Lattner4b37e872006-05-08 21:18:59 +00005766
Dan Gohman75dcf082008-07-31 00:50:31 +00005767 // fold (sext_in_reg (sext x)) -> (sext x)
5768 // fold (sext_in_reg (aext x)) -> (sext x)
5769 // if x is small enough.
5770 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5771 SDValue N00 = N0.getOperand(0);
Evan Cheng003d7c42010-04-16 22:26:19 +00005772 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5773 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005774 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman75dcf082008-07-31 00:50:31 +00005775 }
5776
Chris Lattner95a5e052007-04-17 19:03:21 +00005777 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005778 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005779 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelfdc40a02009-02-17 22:15:04 +00005780
Chris Lattner95a5e052007-04-17 19:03:21 +00005781 // fold operands of sext_in_reg based on knowledge that the top bits are not
5782 // demanded.
Dan Gohman475871a2008-07-27 21:46:04 +00005783 if (SimplifyDemandedBits(SDValue(N, 0)))
5784 return SDValue(N, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00005785
Evan Chengc88138f2007-03-22 01:54:19 +00005786 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5787 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman475871a2008-07-27 21:46:04 +00005788 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00005789 if (NarrowLoad.getNode())
Evan Chengc88138f2007-03-22 01:54:19 +00005790 return NarrowLoad;
5791
Bill Wendling8509c902009-01-30 22:33:24 +00005792 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005793 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner4b37e872006-05-08 21:18:59 +00005794 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5795 if (N0.getOpcode() == ISD::SRL) {
5796 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman87862e72009-12-11 21:31:27 +00005797 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005798 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner4b37e872006-05-08 21:18:59 +00005799 // extended enough.
Dan Gohmanea859be2007-06-22 14:59:07 +00005800 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman87862e72009-12-11 21:31:27 +00005801 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005802 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005803 N0.getOperand(0), N0.getOperand(1));
Chris Lattner4b37e872006-05-08 21:18:59 +00005804 }
5805 }
Evan Chengc88138f2007-03-22 01:54:19 +00005806
Nate Begemanded49632005-10-13 03:11:28 +00005807 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelfdc40a02009-02-17 22:15:04 +00005808 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greifba36cb52008-08-28 21:40:38 +00005809 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005810 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005811 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005812 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005814 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005815 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005816 LN0->getBasePtr(), EVT,
5817 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005818 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005819 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky4b977312012-12-19 07:50:20 +00005820 AddToWorkList(ExtLoad.getNode());
Dan Gohman475871a2008-07-27 21:46:04 +00005821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005822 }
Sylvestre Ledru94c22712012-09-27 10:14:43 +00005823 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greifba36cb52008-08-28 21:40:38 +00005824 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng83060c52007-03-07 08:07:03 +00005825 N0.hasOneUse() &&
Dan Gohmanb625f2f2008-01-30 00:15:11 +00005826 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00005827 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00005828 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Cheng466685d2006-10-09 20:57:25 +00005829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005830 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling8509c902009-01-30 22:33:24 +00005831 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00005832 LN0->getBasePtr(), EVT,
5833 LN0->getMemOperand());
Chris Lattnerd4771842005-12-14 19:25:30 +00005834 CombineTo(N, ExtLoad);
Gabor Greifba36cb52008-08-28 21:40:38 +00005835 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00005836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begemanded49632005-10-13 03:11:28 +00005837 }
Evan Cheng9568e5c2011-06-21 06:01:08 +00005838
5839 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5840 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5841 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5842 N0.getOperand(1), false);
Stephen Hinesdce4a402014-05-29 02:49:00 -07005843 if (BSwap.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng9568e5c2011-06-21 06:01:08 +00005845 BSwap, N1);
5846 }
5847
Stephen Hines36b56882014-04-23 16:57:46 -07005848 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5849 // into a build_vector.
5850 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5851 SmallVector<SDValue, 8> Elts;
5852 unsigned NumElts = N0->getNumOperands();
5853 unsigned ShAmt = VTBits - EVTBits;
5854
5855 for (unsigned i = 0; i != NumElts; ++i) {
5856 SDValue Op = N0->getOperand(i);
5857 if (Op->getOpcode() == ISD::UNDEF) {
5858 Elts.push_back(Op);
5859 continue;
5860 }
5861
5862 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5863 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5864 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5865 Op.getValueType()));
5866 }
5867
Stephen Hinesdce4a402014-05-29 02:49:00 -07005868 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Stephen Hines36b56882014-04-23 16:57:46 -07005869 }
5870
Dan Gohman475871a2008-07-27 21:46:04 +00005871 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005872}
5873
Dan Gohman475871a2008-07-27 21:46:04 +00005874SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5875 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00005876 EVT VT = N->getValueType(0);
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005877 bool isLE = TLI.isLittleEndian();
Nate Begeman1d4d4142005-09-01 00:19:25 +00005878
5879 // noop truncate
5880 if (N0.getValueType() == N->getValueType(0))
Nate Begeman83e75ec2005-09-06 04:43:02 +00005881 return N0;
Nate Begeman1d4d4142005-09-01 00:19:25 +00005882 // fold (truncate c1) -> c1
Chris Lattner310b5782006-05-06 23:06:26 +00005883 if (isa<ConstantSDNode>(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00005884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005885 // fold (truncate (truncate x)) -> (truncate x)
5886 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickac6d9be2013-05-25 02:42:55 +00005887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman1d4d4142005-09-01 00:19:25 +00005888 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner7f893c02010-04-07 18:13:33 +00005889 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5890 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattnerb72773b2006-05-05 22:56:26 +00005891 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00005892 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005893 // if the source is smaller than the dest, we still need an extend
Andrew Trickac6d9be2013-05-25 02:42:55 +00005894 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00005895 N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005896 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman1d4d4142005-09-01 00:19:25 +00005897 // if the source is larger than the dest, than we just need the truncate
Andrew Trickac6d9be2013-05-25 02:42:55 +00005898 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper0eb5dad2012-09-29 07:18:53 +00005899 // if the source and dest are the same type, we can drop both the extend
5900 // and the truncate.
5901 return N0.getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00005902 }
Evan Cheng007b69e2007-03-21 20:14:05 +00005903
Nadav Rotemcc870a82012-02-05 11:39:23 +00005904 // Fold extract-and-trunc into a narrow extract. For example:
5905 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5906 // i32 y = TRUNCATE(i64 x)
5907 // -- becomes --
5908 // v16i8 b = BITCAST (v2i64 val)
5909 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5910 //
5911 // Note: We only run this optimization after type legalization (which often
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005912 // creates this pattern) and before operation legalization after which
5913 // we need to be more careful about the vector instructions that we generate.
5914 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Stephen Hines36b56882014-04-23 16:57:46 -07005915 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005916
5917 EVT VecTy = N0.getOperand(0).getValueType();
5918 EVT ExTy = N0.getValueType();
5919 EVT TrTy = N->getValueType(0);
5920
5921 unsigned NumElem = VecTy.getVectorNumElements();
5922 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5923
5924 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5925 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5926
5927 SDValue EltNo = N0->getOperand(1);
5928 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5929 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellard425b76c2013-08-05 22:22:01 +00005930 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005931 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5932
Andrew Trickac6d9be2013-05-25 02:42:55 +00005933 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005934 NVT, N0.getOperand(0));
5935
5936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005937 SDLoc(N), TrTy, V,
Jim Grosbacha249f7d2012-05-08 20:56:07 +00005938 DAG.getConstant(Index, IndexTy));
Nadav Rotem7e413e9c2012-02-03 13:18:25 +00005939 }
5940 }
5941
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00005942 // Fold a series of buildvector, bitcast, and truncate if possible.
5943 // For example fold
5944 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5945 // (2xi32 (buildvector x, y)).
5946 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5947 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5948 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5949 N0.getOperand(0).hasOneUse()) {
5950
5951 SDValue BuildVect = N0.getOperand(0);
5952 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5953 EVT TruncVecEltTy = VT.getVectorElementType();
5954
5955 // Check that the element types match.
5956 if (BuildVectEltTy == TruncVecEltTy) {
5957 // Now we only need to compute the offset of the truncated elements.
5958 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5959 unsigned TruncVecNumElts = VT.getVectorNumElements();
5960 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5961
5962 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5963 "Invalid number of elements");
5964
5965 SmallVector<SDValue, 8> Opnds;
5966 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5967 Opnds.push_back(BuildVect.getOperand(i));
5968
Stephen Hinesdce4a402014-05-29 02:49:00 -07005969 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighoferc46e2df2013-02-20 21:33:32 +00005970 }
5971 }
5972
Chris Lattner2b4c2792007-10-13 06:35:54 +00005973 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005974 // only the low bits are being used.
5975 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemfcd96192011-02-27 07:40:43 +00005976 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005977 // may have different active low bits.
5978 if (!VT.isVector()) {
5979 SDValue Shorter =
5980 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5981 VT.getSizeInBits()));
5982 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00005983 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem8c20ec52011-02-24 21:01:34 +00005984 }
Nate Begeman3df4d522005-10-12 20:40:40 +00005985 // fold (truncate (load x)) -> (smaller load x)
Evan Cheng007b69e2007-03-21 20:14:05 +00005986 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman4e39e9d2010-06-24 14:30:44 +00005987 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5988 SDValue Reduced = ReduceLoadWidth(N);
5989 if (Reduced.getNode())
5990 return Reduced;
Stephen Hines36b56882014-04-23 16:57:46 -07005991 // Handle the case where the load remains an extending load even
5992 // after truncation.
5993 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5994 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5995 if (!LN0->isVolatile() &&
5996 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5997 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5998 VT, LN0->getChain(), LN0->getBasePtr(),
5999 LN0->getMemoryVT(),
6000 LN0->getMemOperand());
6001 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6002 return NewLoad;
6003 }
6004 }
Dan Gohman4e39e9d2010-06-24 14:30:44 +00006005 }
Michael Liao07edaf32012-10-17 23:45:54 +00006006 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6007 // where ... are all 'undef'.
6008 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6009 SmallVector<EVT, 8> VTs;
6010 SDValue V;
6011 unsigned Idx = 0;
6012 unsigned NumDefs = 0;
6013
6014 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6015 SDValue X = N0.getOperand(i);
6016 if (X.getOpcode() != ISD::UNDEF) {
6017 V = X;
6018 Idx = i;
6019 NumDefs++;
6020 }
6021 // Stop if more than one members are non-undef.
6022 if (NumDefs > 1)
6023 break;
6024 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6025 VT.getVectorElementType(),
6026 X.getValueType().getVectorNumElements()));
6027 }
6028
6029 if (NumDefs == 0)
6030 return DAG.getUNDEF(VT);
6031
6032 if (NumDefs == 1) {
6033 assert(V.getNode() && "The single defined operand is empty!");
6034 SmallVector<SDValue, 8> Opnds;
6035 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6036 if (i != Idx) {
6037 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6038 continue;
6039 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00006040 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao07edaf32012-10-17 23:45:54 +00006041 AddToWorkList(NV.getNode());
6042 Opnds.push_back(NV);
6043 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07006044 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao07edaf32012-10-17 23:45:54 +00006045 }
6046 }
Dan Gohman4e39e9d2010-06-24 14:30:44 +00006047
6048 // Simplify the operands using demanded-bits information.
6049 if (!VT.isVector() &&
6050 SimplifyDemandedBits(SDValue(N, 0)))
6051 return SDValue(N, 0);
6052
Evan Chenge5b51ac2010-04-17 06:13:15 +00006053 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006054}
6055
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006056static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman475871a2008-07-27 21:46:04 +00006057 SDValue Elt = N->getOperand(i);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006058 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greifba36cb52008-08-28 21:40:38 +00006059 return Elt.getNode();
6060 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006061}
6062
6063/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelfdc40a02009-02-17 22:15:04 +00006064/// if load locations are consecutive.
Owen Andersone50ed302009-08-10 22:56:29 +00006065SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006066 assert(N->getOpcode() == ISD::BUILD_PAIR);
6067
Nate Begemanabc01992009-06-05 21:37:30 +00006068 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6069 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerfa459012010-09-21 16:08:50 +00006070 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Stephen Hines36b56882014-04-23 16:57:46 -07006071 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman475871a2008-07-27 21:46:04 +00006072 return SDValue();
Owen Andersone50ed302009-08-10 22:56:29 +00006073 EVT LD1VT = LD1->getValueType(0);
Bill Wendling67a67682009-01-30 22:44:24 +00006074
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006075 if (ISD::isNON_EXTLoad(LD2) &&
6076 LD2->hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006077 // If both are volatile this would reduce the number of volatile loads.
6078 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begemanabc01992009-06-05 21:37:30 +00006079 !LD1->isVolatile() &&
6080 !LD2->isVolatile() &&
Evan Cheng64fa4a92009-12-09 01:36:00 +00006081 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begemanabc01992009-06-05 21:37:30 +00006082 unsigned Align = LD1->getAlignment();
Micah Villmow3574eca2012-10-08 16:38:25 +00006083 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00006084 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling67a67682009-01-30 22:44:24 +00006085
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006086 if (NewAlign <= Align &&
Duncan Sands25cf2272008-11-24 14:53:14 +00006087 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006088 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00006089 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00006090 false, false, false, Align);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006091 }
Bill Wendling67a67682009-01-30 22:44:24 +00006092
Dan Gohman475871a2008-07-27 21:46:04 +00006093 return SDValue();
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006094}
6095
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006096SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman475871a2008-07-27 21:46:04 +00006097 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00006098 EVT VT = N->getValueType(0);
Chris Lattner94683772005-12-23 05:30:37 +00006099
Dan Gohman7f321562007-06-25 16:23:39 +00006100 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6101 // Only do this before legalize, since afterward the target may be depending
6102 // on the bitconvert.
6103 // First check to see if this is all constant.
Duncan Sands25cf2272008-11-24 14:53:14 +00006104 if (!LegalTypes &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006105 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00006106 VT.isVector()) {
Stephen Hines36b56882014-04-23 16:57:46 -07006107 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelfdc40a02009-02-17 22:15:04 +00006108
Owen Andersone50ed302009-08-10 22:56:29 +00006109 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00006110 assert(!DestEltVT.isVector() &&
Dan Gohman7f321562007-06-25 16:23:39 +00006111 "Element type of vector ValueType must not be vector!");
Bill Wendling67a67682009-01-30 22:44:24 +00006112 if (isSimple)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006113 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohman7f321562007-06-25 16:23:39 +00006114 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006115
Dan Gohman3dd168d2008-09-05 01:58:21 +00006116 // If the input is a constant, let getNode fold it.
Chris Lattner94683772005-12-23 05:30:37 +00006117 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006118 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohmana407ca12009-08-10 23:15:10 +00006119 if (Res.getNode() != N) {
6120 if (!LegalOperations ||
6121 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6122 return Res;
6123
6124 // Folding it resulted in an illegal node, and it's too late to
6125 // do that. Clean up the old node and forego the transformation.
6126 // Ideally this won't happen very often, because instcombine
6127 // and the earlier dagcombine runs (where illegal nodes are
6128 // permitted) should have folded most of them already.
6129 DAG.DeleteNode(Res.getNode());
6130 }
Chris Lattner94683772005-12-23 05:30:37 +00006131 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006132
Bill Wendling67a67682009-01-30 22:44:24 +00006133 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006134 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006135 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006136 N0.getOperand(0));
Chris Lattner6258fb22006-04-02 02:53:43 +00006137
Chris Lattner57104102005-12-23 05:44:41 +00006138 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng513da432007-10-06 08:19:55 +00006139 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greifba36cb52008-08-28 21:40:38 +00006140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006141 // Do not change the width of a volatile load.
6142 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenault509a4922013-11-15 04:42:23 +00006143 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6144 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Cheng466685d2006-10-09 20:57:25 +00006145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmow3574eca2012-10-08 16:38:25 +00006146 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00006147 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Cheng59d5b682007-05-07 21:27:48 +00006148 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling67a67682009-01-30 22:44:24 +00006149
Evan Cheng59d5b682007-05-07 21:27:48 +00006150 if (Align <= OrigAlign) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006151 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerfa459012010-09-21 16:08:50 +00006152 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00006153 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00006154 LN0->isInvariant(), OrigAlign,
6155 LN0->getTBAAInfo());
Evan Cheng59d5b682007-05-07 21:27:48 +00006156 AddToWorkList(N);
Gabor Greif12632d22008-08-30 19:29:20 +00006157 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00006158 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006159 N0.getValueType(), Load),
Evan Cheng59d5b682007-05-07 21:27:48 +00006160 Load.getValue(1));
6161 return Load;
6162 }
Chris Lattner57104102005-12-23 05:44:41 +00006163 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00006164
Bill Wendling67a67682009-01-30 22:44:24 +00006165 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6166 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner3bd39d42008-01-27 17:42:27 +00006167 // This often reduces constant pool loads.
Tom Stellard1f67c632013-07-23 23:55:03 +00006168 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6169 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem91a7e012012-09-13 14:54:28 +00006170 N0.getNode()->hasOneUse() && VT.isInteger() &&
6171 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006172 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006173 N0.getOperand(0));
Gabor Greifba36cb52008-08-28 21:40:38 +00006174 AddToWorkList(NewConv.getNode());
Scott Michelfdc40a02009-02-17 22:15:04 +00006175
Duncan Sands83ec4b62008-06-06 12:08:01 +00006176 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006177 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006178 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006179 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00006180 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006181 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006182 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner3bd39d42008-01-27 17:42:27 +00006183 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006184
Bill Wendling67a67682009-01-30 22:44:24 +00006185 // fold (bitconvert (fcopysign cst, x)) ->
6186 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6187 // Note that we don't handle (copysign x, cst) because this can always be
6188 // folded to an fneg or fabs.
Gabor Greifba36cb52008-08-28 21:40:38 +00006189 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattnerf32aac32008-01-27 23:32:17 +00006190 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00006191 VT.isInteger() && !VT.isVector()) {
6192 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson23b9b192009-08-12 00:36:31 +00006193 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner2392ae72010-04-15 04:48:01 +00006194 if (isTypeLegal(IntXVT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006195 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006196 IntXVT, N0.getOperand(1));
Duncan Sands25cf2272008-11-24 14:53:14 +00006197 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006198
Duncan Sands25cf2272008-11-24 14:53:14 +00006199 // If X has a different width than the result/lhs, sext it or truncate it.
6200 unsigned VTWidth = VT.getSizeInBits();
6201 if (OrigXWidth < VTWidth) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006202 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00006203 AddToWorkList(X.getNode());
6204 } else if (OrigXWidth > VTWidth) {
6205 // To get the sign bit in the right place, we have to shift it right
6206 // before truncating.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006207 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling67a67682009-01-30 22:44:24 +00006208 X.getValueType(), X,
Duncan Sands25cf2272008-11-24 14:53:14 +00006209 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6210 AddToWorkList(X.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006211 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sands25cf2272008-11-24 14:53:14 +00006212 AddToWorkList(X.getNode());
6213 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006214
Duncan Sands25cf2272008-11-24 14:53:14 +00006215 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006216 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006217 X, DAG.getConstant(SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00006218 AddToWorkList(X.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006219
Andrew Trickac6d9be2013-05-25 02:42:55 +00006220 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling67a67682009-01-30 22:44:24 +00006221 VT, N0.getOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006222 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling67a67682009-01-30 22:44:24 +00006223 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sands25cf2272008-11-24 14:53:14 +00006224 AddToWorkList(Cst.getNode());
Chris Lattner3bd39d42008-01-27 17:42:27 +00006225
Andrew Trickac6d9be2013-05-25 02:42:55 +00006226 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sands25cf2272008-11-24 14:53:14 +00006227 }
Chris Lattner3bd39d42008-01-27 17:42:27 +00006228 }
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006229
Sylvestre Ledru94c22712012-09-27 10:14:43 +00006230 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006231 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greifba36cb52008-08-28 21:40:38 +00006232 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6233 if (CombineLD.getNode())
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006234 return CombineLD;
6235 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006236
Dan Gohman475871a2008-07-27 21:46:04 +00006237 return SDValue();
Chris Lattner94683772005-12-23 05:30:37 +00006238}
6239
Dan Gohman475871a2008-07-27 21:46:04 +00006240SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +00006241 EVT VT = N->getValueType(0);
Evan Cheng9bfa03c2008-05-12 23:04:07 +00006242 return CombineConsecutiveLoads(N, VT);
6243}
6244
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006245/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelfdc40a02009-02-17 22:15:04 +00006246/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattner6258fb22006-04-02 02:53:43 +00006247/// destination element value type.
Dan Gohman475871a2008-07-27 21:46:04 +00006248SDValue DAGCombiner::
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006249ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Andersone50ed302009-08-10 22:56:29 +00006250 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelfdc40a02009-02-17 22:15:04 +00006251
Chris Lattner6258fb22006-04-02 02:53:43 +00006252 // If this is already the right type, we're done.
Dan Gohman475871a2008-07-27 21:46:04 +00006253 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006254
Duncan Sands83ec4b62008-06-06 12:08:01 +00006255 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6256 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelfdc40a02009-02-17 22:15:04 +00006257
Chris Lattner6258fb22006-04-02 02:53:43 +00006258 // If this is a conversion of N elements of one type to N elements of another
6259 // type, convert each element. This handles FP<->INT cases.
6260 if (SrcBitSize == DstBitSize) {
Nate Begemane0efc212010-07-27 18:02:18 +00006261 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6262 BV->getValueType(0).getVectorNumElements());
6263
6264 // Due to the FP element handling below calling this routine recursively,
6265 // we can end up with a scalar-to-vector node here.
6266 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006267 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6268 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begemane0efc212010-07-27 18:02:18 +00006269 DstEltVT, BV->getOperand(0)));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006270
Dan Gohman475871a2008-07-27 21:46:04 +00006271 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00006272 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilsonb1303d02009-04-13 22:05:19 +00006273 SDValue Op = BV->getOperand(i);
6274 // If the vector element type is not legal, the BUILD_VECTOR operands
6275 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonc8851652009-04-20 17:27:09 +00006276 if (Op.getValueType() != SrcEltVT)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006277 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6278 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilsonb1303d02009-04-13 22:05:19 +00006279 DstEltVT, Op));
Gabor Greifba36cb52008-08-28 21:40:38 +00006280 AddToWorkList(Ops.back().getNode());
Chris Lattner3e104b12006-04-08 04:15:24 +00006281 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07006282 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattner6258fb22006-04-02 02:53:43 +00006283 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006284
Chris Lattner6258fb22006-04-02 02:53:43 +00006285 // Otherwise, we're growing or shrinking the elements. To avoid having to
6286 // handle annoying details of growing/shrinking FP values, we convert them to
6287 // int first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006288 if (SrcEltVT.isFloatingPoint()) {
Chris Lattner6258fb22006-04-02 02:53:43 +00006289 // Convert the input float vector to a int vector where the elements are the
6290 // same sizes.
Owen Anderson825b72b2009-08-11 20:47:22 +00006291 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00006292 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006293 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattner6258fb22006-04-02 02:53:43 +00006294 SrcEltVT = IntVT;
6295 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006296
Chris Lattner6258fb22006-04-02 02:53:43 +00006297 // Now we know the input is an integer vector. If the output is a FP type,
6298 // convert to integer first, then to FP of the right size.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006299 if (DstEltVT.isFloatingPoint()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00006300 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson23b9b192009-08-12 00:36:31 +00006301 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006302 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelfdc40a02009-02-17 22:15:04 +00006303
Chris Lattner6258fb22006-04-02 02:53:43 +00006304 // Next, convert to FP elements of the same size.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006305 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattner6258fb22006-04-02 02:53:43 +00006306 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006307
Chris Lattner6258fb22006-04-02 02:53:43 +00006308 // Okay, we know the src/dst types are both integers of differing types.
6309 // Handling growing first.
Duncan Sands83ec4b62008-06-06 12:08:01 +00006310 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattner6258fb22006-04-02 02:53:43 +00006311 if (SrcBitSize < DstBitSize) {
6312 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelfdc40a02009-02-17 22:15:04 +00006313
Dan Gohman475871a2008-07-27 21:46:04 +00006314 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +00006315 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattner6258fb22006-04-02 02:53:43 +00006316 i += NumInputsPerOutput) {
6317 bool isLE = TLI.isLittleEndian();
Dan Gohman220a8232008-03-03 23:51:38 +00006318 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattner6258fb22006-04-02 02:53:43 +00006319 bool EltIsUndef = true;
6320 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6321 // Shift the previously computed bits over.
6322 NewBits <<= SrcBitSize;
Dan Gohman475871a2008-07-27 21:46:04 +00006323 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattner6258fb22006-04-02 02:53:43 +00006324 if (Op.getOpcode() == ISD::UNDEF) continue;
6325 EltIsUndef = false;
Scott Michelfdc40a02009-02-17 22:15:04 +00006326
Jay Foad40f8f622010-12-07 08:25:19 +00006327 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohman58c25872010-04-12 02:24:01 +00006328 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006329 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006330
Chris Lattner6258fb22006-04-02 02:53:43 +00006331 if (EltIsUndef)
Dale Johannesene8d72302009-02-06 23:05:02 +00006332 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00006333 else
6334 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6335 }
6336
Owen Anderson23b9b192009-08-12 00:36:31 +00006337 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Stephen Hinesdce4a402014-05-29 02:49:00 -07006338 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattner6258fb22006-04-02 02:53:43 +00006339 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006340
Chris Lattner6258fb22006-04-02 02:53:43 +00006341 // Finally, this must be the case where we are shrinking elements: each input
6342 // turns into multiple outputs.
Evan Chengefec7512008-02-18 23:04:32 +00006343 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattner6258fb22006-04-02 02:53:43 +00006344 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson23b9b192009-08-12 00:36:31 +00006345 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6346 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman475871a2008-07-27 21:46:04 +00006347 SmallVector<SDValue, 8> Ops;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006348
Dan Gohman7f321562007-06-25 16:23:39 +00006349 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattner6258fb22006-04-02 02:53:43 +00006350 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6351 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesene8d72302009-02-06 23:05:02 +00006352 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattner6258fb22006-04-02 02:53:43 +00006353 continue;
6354 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006355
Jay Foad40f8f622010-12-07 08:25:19 +00006356 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6357 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006358
Chris Lattner6258fb22006-04-02 02:53:43 +00006359 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad40f8f622010-12-07 08:25:19 +00006360 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006361 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad40f8f622010-12-07 08:25:19 +00006362 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Chengefec7512008-02-18 23:04:32 +00006363 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006364 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingb0162f52009-01-30 22:53:48 +00006365 Ops[0]);
Dan Gohman220a8232008-03-03 23:51:38 +00006366 OpVal = OpVal.lshr(DstBitSize);
Chris Lattner6258fb22006-04-02 02:53:43 +00006367 }
6368
6369 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands0753fc12008-02-11 10:37:04 +00006370 if (TLI.isBigEndian())
Chris Lattner6258fb22006-04-02 02:53:43 +00006371 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6372 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006373
Stephen Hinesdce4a402014-05-29 02:49:00 -07006374 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattner6258fb22006-04-02 02:53:43 +00006375}
6376
Dan Gohman475871a2008-07-27 21:46:04 +00006377SDValue DAGCombiner::visitFADD(SDNode *N) {
6378 SDValue N0 = N->getOperand(0);
6379 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006380 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6381 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006382 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006383
Dan Gohman7f321562007-06-25 16:23:39 +00006384 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006385 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006386 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006387 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006388 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006389
Lang Hames01806942012-06-14 20:37:15 +00006390 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006391 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006392 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006393 // canonicalize constant to RHS
6394 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006395 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006396 // fold (fadd A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006397 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6398 N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006399 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006400 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006401 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006402 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006403 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006404 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingb0162f52009-01-30 22:53:48 +00006405 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Andersonafd3d562012-03-06 00:29:31 +00006406 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem6dfabb62012-09-20 08:53:31 +00006407 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006408 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sands25cf2272008-11-24 14:53:14 +00006409 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006410
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006411 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006412 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6413 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6414 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006415 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6416 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlingfc4b6772009-02-01 11:19:36 +00006417 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006418
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006419 // No FP constant should be created after legalization as Instruction
6420 // Selection pass has hard time in dealing with FP constant.
6421 //
6422 // We don't need test this condition for transformation like following, as
6423 // the DAG being transformed implies it is legal to take FP constant as
6424 // operand.
Stephen Lin155615d2013-07-08 00:37:03 +00006425 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006426 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lin155615d2013-07-08 00:37:03 +00006427 //
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006428 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6429
Owen Anderson607ebde2012-11-01 02:00:53 +00006430 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006431 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006432 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Anderson607ebde2012-11-01 02:00:53 +00006433 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006434
6435 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006436 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Linb4940152013-07-09 00:44:49 +00006437 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Anderson607ebde2012-11-01 02:00:53 +00006438 return DAG.getConstantFP(0.0, VT);
Owen Anderson607ebde2012-11-01 02:00:53 +00006439
Owen Anderson43da6c72012-08-30 23:35:16 +00006440 // In unsafe math mode, we can fold chains of FADD's of the same value
6441 // into multiplications. This transform is not safe in general because
6442 // we are reducing the number of rounding steps.
6443 if (DAG.getTarget().Options.UnsafeFPMath &&
6444 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6445 !N0CFP && !N1CFP) {
6446 if (N0.getOpcode() == ISD::FMUL) {
6447 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6448 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6449
Stephen Lin38103d12013-06-14 18:17:35 +00006450 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006451 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006452 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006453 SDValue(CFP00, 0),
6454 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006455 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006456 N1, NewCFP);
6457 }
6458
Stephen Lin38103d12013-06-14 18:17:35 +00006459 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006460 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006461 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006462 SDValue(CFP01, 0),
6463 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006464 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006465 N1, NewCFP);
6466 }
6467
Stephen Lin38103d12013-06-14 18:17:35 +00006468 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006469 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6470 N1.getOperand(0) == N1.getOperand(1) &&
6471 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006472 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006473 SDValue(CFP00, 0),
6474 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006475 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006476 N0.getOperand(1), NewCFP);
6477 }
6478
Stephen Lin38103d12013-06-14 18:17:35 +00006479 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Anderson43da6c72012-08-30 23:35:16 +00006480 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6481 N1.getOperand(0) == N1.getOperand(1) &&
6482 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006483 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006484 SDValue(CFP01, 0),
6485 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006486 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006487 N0.getOperand(0), NewCFP);
6488 }
6489 }
6490
6491 if (N1.getOpcode() == ISD::FMUL) {
6492 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6493 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6494
Stephen Lin38103d12013-06-14 18:17:35 +00006495 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006496 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006497 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006498 SDValue(CFP10, 0),
6499 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006500 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006501 N0, NewCFP);
6502 }
6503
Stephen Lin38103d12013-06-14 18:17:35 +00006504 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Anderson43da6c72012-08-30 23:35:16 +00006505 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006506 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006507 SDValue(CFP11, 0),
6508 DAG.getConstantFP(1.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006509 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006510 N0, NewCFP);
6511 }
6512
Owen Anderson43da6c72012-08-30 23:35:16 +00006513
Stephen Lin38103d12013-06-14 18:17:35 +00006514 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6515 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6516 N0.getOperand(0) == N0.getOperand(1) &&
6517 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006518 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006519 SDValue(CFP10, 0),
6520 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006521 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006522 N1.getOperand(1), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006523 }
6524
Stephen Lin38103d12013-06-14 18:17:35 +00006525 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6526 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6527 N0.getOperand(0) == N0.getOperand(1) &&
6528 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006529 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006530 SDValue(CFP11, 0),
6531 DAG.getConstantFP(2.0, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00006532 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Lin38103d12013-06-14 18:17:35 +00006533 N1.getOperand(0), NewCFP);
Owen Anderson43da6c72012-08-30 23:35:16 +00006534 }
6535 }
6536
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006537 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006538 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006539 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006540 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006541 (N0.getOperand(0) == N1))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006542 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006543 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006544 }
6545
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006546 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yang98b93e52013-02-02 00:22:03 +00006547 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lina553bed2013-06-14 21:33:58 +00006548 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yang98b93e52013-02-02 00:22:03 +00006549 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006550 N1.getOperand(0) == N0)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006551 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yang98b93e52013-02-02 00:22:03 +00006552 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yang98b93e52013-02-02 00:22:03 +00006553 }
6554
Stephen Lina553bed2013-06-14 21:33:58 +00006555 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang1cd1d022013-03-25 22:52:29 +00006556 if (AllowNewFpConst &&
6557 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Anderson43da6c72012-08-30 23:35:16 +00006558 N0.getOperand(0) == N0.getOperand(1) &&
6559 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Linb4940152013-07-09 00:44:49 +00006560 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006561 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson43da6c72012-08-30 23:35:16 +00006562 N0.getOperand(0),
6563 DAG.getConstantFP(4.0, VT));
Owen Anderson43da6c72012-08-30 23:35:16 +00006564 }
6565
Lang Hamesd693caf2012-06-19 22:51:23 +00006566 // FADD -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006567 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006568 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006569 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6570 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006571
6572 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Linb4940152013-07-09 00:44:49 +00006573 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006574 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006575 N0.getOperand(0), N0.getOperand(1), N1);
Owen Anderson43da6c72012-08-30 23:35:16 +00006576
Michael Liaob79bff52012-09-01 04:09:16 +00006577 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hamesd693caf2012-06-19 22:51:23 +00006578 // Note: Commutes FADD operands.
Stephen Linb4940152013-07-09 00:44:49 +00006579 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006580 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006581 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hamesd693caf2012-06-19 22:51:23 +00006582 }
6583
Dan Gohman475871a2008-07-27 21:46:04 +00006584 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006585}
6586
Dan Gohman475871a2008-07-27 21:46:04 +00006587SDValue DAGCombiner::visitFSUB(SDNode *N) {
6588 SDValue N0 = N->getOperand(0);
6589 SDValue N1 = N->getOperand(1);
Nate Begemana0e221d2005-10-18 00:28:13 +00006590 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6591 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006592 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006593 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00006594
Dan Gohman7f321562007-06-25 16:23:39 +00006595 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006596 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006597 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006598 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006599 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006600
Nate Begemana0e221d2005-10-18 00:28:13 +00006601 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006602 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006603 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingb0162f52009-01-30 22:53:48 +00006604 // fold (fsub A, 0) -> A
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006605 if (DAG.getTarget().Options.UnsafeFPMath &&
6606 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohmana90c8e62009-01-23 19:10:37 +00006607 return N0;
Bill Wendlingb0162f52009-01-30 22:53:48 +00006608 // fold (fsub 0, B) -> -B
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006609 if (DAG.getTarget().Options.UnsafeFPMath &&
6610 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006611 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00006612 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman760f86f2009-01-22 21:58:43 +00006613 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006614 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman23ff1822007-07-02 15:48:56 +00006615 }
Bill Wendlingb0162f52009-01-30 22:53:48 +00006616 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Andersonafd3d562012-03-06 00:29:31 +00006617 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006618 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sands25cf2272008-11-24 14:53:14 +00006619 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelfdc40a02009-02-17 22:15:04 +00006620
Bill Wendling5a894342012-03-15 05:12:00 +00006621 // If 'unsafe math' is enabled, fold
Owen Anderson713e9532012-05-07 20:51:25 +00006622 // (fsub x, x) -> 0.0 &
Bill Wendling5a894342012-03-15 05:12:00 +00006623 // (fsub x, (fadd x, y)) -> (fneg y) &
6624 // (fsub x, (fadd y, x)) -> (fneg y)
6625 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Anderson713e9532012-05-07 20:51:25 +00006626 if (N0 == N1)
6627 return DAG.getConstantFP(0.0f, VT);
6628
Bill Wendling5a894342012-03-15 05:12:00 +00006629 if (N1.getOpcode() == ISD::FADD) {
6630 SDValue N10 = N1->getOperand(0);
6631 SDValue N11 = N1->getOperand(1);
6632
6633 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6634 &DAG.getTarget().Options))
6635 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin75d13062013-07-10 20:47:39 +00006636
Stephen Linb4940152013-07-09 00:44:49 +00006637 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6638 &DAG.getTarget().Options))
Bill Wendling5a894342012-03-15 05:12:00 +00006639 return GetNegatedExpression(N10, DAG, LegalOperations);
6640 }
6641 }
6642
Lang Hamesd693caf2012-06-19 22:51:23 +00006643 // FSUB -> FMA combines:
Lang Hamese0231412012-06-22 01:09:09 +00006644 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hamesd693caf2012-06-19 22:51:23 +00006645 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Line54885a2013-07-09 18:16:56 +00006646 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6647 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hamesd693caf2012-06-19 22:51:23 +00006648
6649 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Linb4940152013-07-09 00:44:49 +00006650 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006651 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006652 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006653 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hamesd693caf2012-06-19 22:51:23 +00006654
6655 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6656 // Note: Commutes FSUB operands.
Stephen Lin75d13062013-07-10 20:47:39 +00006657 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006658 return DAG.getNode(ISD::FMA, dl, VT,
6659 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hamesd693caf2012-06-19 22:51:23 +00006660 N1.getOperand(0)),
6661 N1.getOperand(1), N0);
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006662
Stephen Linb4940152013-07-09 00:44:49 +00006663 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lin155615d2013-07-08 00:37:03 +00006664 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky1503aba2012-08-01 12:06:00 +00006665 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6666 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6667 SDValue N00 = N0.getOperand(0).getOperand(0);
6668 SDValue N01 = N0.getOperand(0).getOperand(1);
6669 return DAG.getNode(ISD::FMA, dl, VT,
6670 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6671 DAG.getNode(ISD::FNEG, dl, VT, N1));
6672 }
Lang Hamesd693caf2012-06-19 22:51:23 +00006673 }
6674
Dan Gohman475871a2008-07-27 21:46:04 +00006675 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006676}
6677
Dan Gohman475871a2008-07-27 21:46:04 +00006678SDValue DAGCombiner::visitFMUL(SDNode *N) {
6679 SDValue N0 = N->getOperand(0);
6680 SDValue N1 = N->getOperand(1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006681 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6682 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006683 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006684 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006685
Dan Gohman7f321562007-06-25 16:23:39 +00006686 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006687 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006688 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006689 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006690 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006691
Nate Begeman11af4ea2005-10-17 20:40:11 +00006692 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006693 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006694 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begeman11af4ea2005-10-17 20:40:11 +00006695 // canonicalize constant to RHS
Nate Begemana0e221d2005-10-18 00:28:13 +00006696 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006698 // fold (fmul A, 0) -> 0
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006699 if (DAG.getTarget().Options.UnsafeFPMath &&
6700 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman760f86f2009-01-22 21:58:43 +00006701 return N1;
Dan Gohman77b81fe2009-06-04 17:12:12 +00006702 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006703 if (DAG.getTarget().Options.UnsafeFPMath &&
6704 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman77b81fe2009-06-04 17:12:12 +00006705 return N1;
Owen Anderson363e4b92012-05-02 21:32:35 +00006706 // fold (fmul A, 1.0) -> A
6707 if (N1CFP && N1CFP->isExactlyValue(1.0))
6708 return N0;
Nate Begeman11af4ea2005-10-17 20:40:11 +00006709 // fold (fmul X, 2.0) -> (fadd X, X)
6710 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006711 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmaneb1fedc2009-08-10 16:50:32 +00006712 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattner29446522007-05-14 22:04:50 +00006713 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman760f86f2009-01-22 21:58:43 +00006714 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006715 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006716
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006717 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006718 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006719 &DAG.getTarget().Options)) {
Stephen Lin155615d2013-07-08 00:37:03 +00006720 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006721 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006722 // Both can be negated for free, check to see if at least one is cheaper
6723 // negated.
6724 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006725 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006726 GetNegatedExpression(N0, DAG, LegalOperations),
6727 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006728 }
6729 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006730
Chris Lattnerddae4bd2007-01-08 23:04:05 +00006731 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006732 if (DAG.getTarget().Options.UnsafeFPMath &&
6733 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greifba36cb52008-08-28 21:40:38 +00006734 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006735 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6736 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesende064702009-02-06 21:50:26 +00006737 N0.getOperand(1), N1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006738
Dan Gohman475871a2008-07-27 21:46:04 +00006739 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006740}
6741
Owen Anderson062c0a52012-05-02 22:17:40 +00006742SDValue DAGCombiner::visitFMA(SDNode *N) {
6743 SDValue N0 = N->getOperand(0);
6744 SDValue N1 = N->getOperand(1);
6745 SDValue N2 = N->getOperand(2);
6746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6747 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6748 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00006749 SDLoc dl(N);
Owen Anderson062c0a52012-05-02 22:17:40 +00006750
Owen Anderson607ebde2012-11-01 02:00:53 +00006751 if (DAG.getTarget().Options.UnsafeFPMath) {
6752 if (N0CFP && N0CFP->isZero())
6753 return N2;
6754 if (N1CFP && N1CFP->isZero())
6755 return N2;
6756 }
Owen Anderson062c0a52012-05-02 22:17:40 +00006757 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006758 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006759 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006760 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson062c0a52012-05-02 22:17:40 +00006761
Owen Anderson85ef6f42012-05-30 18:50:39 +00006762 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Andersonf917d202012-05-30 18:54:50 +00006763 if (N0CFP && !N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006764 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Anderson85ef6f42012-05-30 18:50:39 +00006765
Owen Anderson58d57292012-09-01 06:04:27 +00006766 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6767 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6768 N2.getOpcode() == ISD::FMUL &&
6769 N0 == N2.getOperand(0) &&
6770 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6771 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6772 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6773 }
6774
6775
6776 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6777 if (DAG.getTarget().Options.UnsafeFPMath &&
6778 N0.getOpcode() == ISD::FMUL && N1CFP &&
6779 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6780 return DAG.getNode(ISD::FMA, dl, VT,
6781 N0.getOperand(0),
6782 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6783 N2);
6784 }
6785
6786 // (fma x, 1, y) -> (fadd x, y)
6787 // (fma x, -1, y) -> (fadd (fneg x), y)
6788 if (N1CFP) {
6789 if (N1CFP->isExactlyValue(1.0))
6790 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6791
6792 if (N1CFP->isExactlyValue(-1.0) &&
6793 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6794 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6795 AddToWorkList(RHSNeg.getNode());
6796 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6797 }
6798 }
6799
6800 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Linb4940152013-07-09 00:44:49 +00006801 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6802 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006803 DAG.getNode(ISD::FADD, dl, VT,
6804 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006805
6806 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6807 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Linb4940152013-07-09 00:44:49 +00006808 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6809 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson58d57292012-09-01 06:04:27 +00006810 DAG.getNode(ISD::FADD, dl, VT,
6811 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson58d57292012-09-01 06:04:27 +00006812
6813
Owen Anderson062c0a52012-05-02 22:17:40 +00006814 return SDValue();
6815}
6816
Dan Gohman475871a2008-07-27 21:46:04 +00006817SDValue DAGCombiner::visitFDIV(SDNode *N) {
6818 SDValue N0 = N->getOperand(0);
6819 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006820 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6821 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006822 EVT VT = N->getValueType(0);
Owen Andersonafd3d562012-03-06 00:29:31 +00006823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner01b3d732005-09-28 22:28:18 +00006824
Dan Gohman7f321562007-06-25 16:23:39 +00006825 // fold vector ops
Duncan Sands83ec4b62008-06-06 12:08:01 +00006826 if (VT.isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00006827 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greifba36cb52008-08-28 21:40:38 +00006828 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman05d92fe2007-07-13 20:03:40 +00006829 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006830
Nate Begemana148d982006-01-18 22:35:16 +00006831 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigande669c932012-10-29 18:35:49 +00006832 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006833 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006834
Duncan Sands3ef3fcf2012-04-08 18:08:12 +00006835 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigande669c932012-10-29 18:35:49 +00006836 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands961d6662012-04-07 20:04:00 +00006837 // Compute the reciprocal 1.0 / c2.
6838 APFloat N1APF = N1CFP->getValueAPF();
6839 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6840 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands507bb7a2012-04-10 20:35:27 +00006841 // Only do the transform if the reciprocal is a legal fp immediate that
6842 // isn't too nasty (eg NaN, denormal, ...).
6843 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov999821c2012-04-10 13:22:49 +00006844 (!LegalOperations ||
6845 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6846 // backend)... we should handle this gracefully after Legalize.
6847 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6848 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6849 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006850 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands961d6662012-04-07 20:04:00 +00006851 DAG.getConstantFP(Recip, VT));
6852 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006853
Bill Wendlinga03e74b2009-01-30 22:57:07 +00006854 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Andersonafd3d562012-03-06 00:29:31 +00006855 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006856 &DAG.getTarget().Options)) {
Owen Andersonafd3d562012-03-06 00:29:31 +00006857 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006858 &DAG.getTarget().Options)) {
Chris Lattner29446522007-05-14 22:04:50 +00006859 // Both can be negated for free, check to see if at least one is cheaper
6860 // negated.
6861 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006862 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sands25cf2272008-11-24 14:53:14 +00006863 GetNegatedExpression(N0, DAG, LegalOperations),
6864 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattner29446522007-05-14 22:04:50 +00006865 }
6866 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006867
Dan Gohman475871a2008-07-27 21:46:04 +00006868 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006869}
6870
Dan Gohman475871a2008-07-27 21:46:04 +00006871SDValue DAGCombiner::visitFREM(SDNode *N) {
6872 SDValue N0 = N->getOperand(0);
6873 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00006874 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6875 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006876 EVT VT = N->getValueType(0);
Chris Lattner01b3d732005-09-28 22:28:18 +00006877
Nate Begemana148d982006-01-18 22:35:16 +00006878 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigande669c932012-10-29 18:35:49 +00006879 if (N0CFP && N1CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006880 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohman7f321562007-06-25 16:23:39 +00006881
Dan Gohman475871a2008-07-27 21:46:04 +00006882 return SDValue();
Chris Lattner01b3d732005-09-28 22:28:18 +00006883}
6884
Dan Gohman475871a2008-07-27 21:46:04 +00006885SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6886 SDValue N0 = N->getOperand(0);
6887 SDValue N1 = N->getOperand(1);
Chris Lattner12d83032006-03-05 05:30:57 +00006888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6889 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Andersone50ed302009-08-10 22:56:29 +00006890 EVT VT = N->getValueType(0);
Chris Lattner12d83032006-03-05 05:30:57 +00006891
Ulrich Weigande669c932012-10-29 18:35:49 +00006892 if (N0CFP && N1CFP) // Constant fold
Andrew Trickac6d9be2013-05-25 02:42:55 +00006893 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00006894
Chris Lattner12d83032006-03-05 05:30:57 +00006895 if (N1CFP) {
Dale Johannesene6c17422007-08-26 01:18:27 +00006896 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru94c22712012-09-27 10:14:43 +00006897 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6898 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman760f86f2009-01-22 21:58:43 +00006899 if (!V.isNegative()) {
6900 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006901 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman760f86f2009-01-22 21:58:43 +00006902 } else {
6903 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006904 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6905 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman760f86f2009-01-22 21:58:43 +00006906 }
Chris Lattner12d83032006-03-05 05:30:57 +00006907 }
Scott Michelfdc40a02009-02-17 22:15:04 +00006908
Chris Lattner12d83032006-03-05 05:30:57 +00006909 // copysign(fabs(x), y) -> copysign(x, y)
6910 // copysign(fneg(x), y) -> copysign(x, y)
6911 // copysign(copysign(x,z), y) -> copysign(x, y)
6912 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6913 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006914 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006915 N0.getOperand(0), N1);
Chris Lattner12d83032006-03-05 05:30:57 +00006916
6917 // copysign(x, abs(y)) -> abs(x)
6918 if (N1.getOpcode() == ISD::FABS)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006919 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006920
Chris Lattner12d83032006-03-05 05:30:57 +00006921 // copysign(x, copysign(y,z)) -> copysign(x, z)
6922 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006923 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006924 N0, N1.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00006925
Chris Lattner12d83032006-03-05 05:30:57 +00006926 // copysign(x, fp_extend(y)) -> copysign(x, y)
6927 // copysign(x, fp_round(y)) -> copysign(x, y)
6928 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickac6d9be2013-05-25 02:42:55 +00006929 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00006930 N0, N1.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00006931
Dan Gohman475871a2008-07-27 21:46:04 +00006932 return SDValue();
Chris Lattner12d83032006-03-05 05:30:57 +00006933}
6934
Dan Gohman475871a2008-07-27 21:46:04 +00006935SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6936 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00006937 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006938 EVT VT = N->getValueType(0);
6939 EVT OpVT = N0.getValueType();
Chris Lattnercda88752008-06-26 00:16:49 +00006940
Nate Begeman1d4d4142005-09-01 00:19:25 +00006941 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006942 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00006943 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00006944 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00006945 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006946 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00006947
Chris Lattnercda88752008-06-26 00:16:49 +00006948 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6949 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00006950 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6951 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00006952 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00006953 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00006954 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00006955 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00006956
Stephen Hines36b56882014-04-23 16:57:46 -07006957 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotemed1a3352012-07-23 07:59:50 +00006958 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6959 // having to say they don't support SELECT_CC on every type the DAG knows
6960 // about, since there is no way to mark an opcode illegal at all value types
6961 // (See also visitSELECT)
6962 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6963 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6964 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6965 !VT.isVector() &&
6966 (!LegalOperations ||
6967 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6968 SDValue Ops[] =
6969 { N0.getOperand(0), N0.getOperand(1),
6970 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6971 N0.getOperand(2) };
Stephen Hinesdce4a402014-05-29 02:49:00 -07006972 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotemed1a3352012-07-23 07:59:50 +00006973 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00006974
Nadav Rotemed1a3352012-07-23 07:59:50 +00006975 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6976 // (select_cc x, y, 1.0, 0.0,, cc)
6977 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6978 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6979 (!LegalOperations ||
6980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6981 SDValue Ops[] =
6982 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6983 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6984 N0.getOperand(0).getOperand(2) };
Stephen Hinesdce4a402014-05-29 02:49:00 -07006985 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotemed1a3352012-07-23 07:59:50 +00006986 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00006987 }
6988
Dan Gohman475871a2008-07-27 21:46:04 +00006989 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00006990}
6991
Dan Gohman475871a2008-07-27 21:46:04 +00006992SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6993 SDValue N0 = N->getOperand(0);
Nate Begeman646d7e22005-09-02 21:18:40 +00006994 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00006995 EVT VT = N->getValueType(0);
6996 EVT OpVT = N0.getValueType();
Nate Begemana148d982006-01-18 22:35:16 +00006997
Nate Begeman1d4d4142005-09-01 00:19:25 +00006998 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00006999 if (N0C &&
Stuart Hastings7e334182011-03-02 19:36:30 +00007000 // ...but only if the target supports immediate floating-point values
Eli Friedman50185242011-11-12 00:35:34 +00007001 (!LegalOperations ||
Evan Cheng9568e5c2011-06-21 06:01:08 +00007002 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007003 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007004
Chris Lattnercda88752008-06-26 00:16:49 +00007005 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7006 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohmanf560ffa2009-01-28 17:46:25 +00007007 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7008 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00007009 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnercda88752008-06-26 00:16:49 +00007010 if (DAG.SignBitIsZero(N0))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007011 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnercda88752008-06-26 00:16:49 +00007012 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007013
Stephen Hines36b56882014-04-23 16:57:46 -07007014 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotemed1a3352012-07-23 07:59:50 +00007015 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7016 // having to say they don't support SELECT_CC on every type the DAG knows
7017 // about, since there is no way to mark an opcode illegal at all value types
7018 // (See also visitSELECT)
7019 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7020 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond9bf71f2012-07-09 20:31:12 +00007021
Nadav Rotemed1a3352012-07-23 07:59:50 +00007022 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7023 (!LegalOperations ||
7024 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7025 SDValue Ops[] =
7026 { N0.getOperand(0), N0.getOperand(1),
7027 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7028 N0.getOperand(2) };
Stephen Hinesdce4a402014-05-29 02:49:00 -07007029 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotemed1a3352012-07-23 07:59:50 +00007030 }
7031 }
Owen Andersond9bf71f2012-07-09 20:31:12 +00007032
Dan Gohman475871a2008-07-27 21:46:04 +00007033 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007034}
7035
Dan Gohman475871a2008-07-27 21:46:04 +00007036SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7037 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007038 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007039 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007040
Nate Begeman1d4d4142005-09-01 00:19:25 +00007041 // fold (fp_to_sint c1fp) -> c1
Nate Begeman646d7e22005-09-02 21:18:40 +00007042 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007043 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007044
Dan Gohman475871a2008-07-27 21:46:04 +00007045 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007046}
7047
Dan Gohman475871a2008-07-27 21:46:04 +00007048SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7049 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007050 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007051 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007052
Nate Begeman1d4d4142005-09-01 00:19:25 +00007053 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigande669c932012-10-29 18:35:49 +00007054 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007055 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007056
Dan Gohman475871a2008-07-27 21:46:04 +00007057 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007058}
7059
Dan Gohman475871a2008-07-27 21:46:04 +00007060SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7061 SDValue N0 = N->getOperand(0);
7062 SDValue N1 = N->getOperand(1);
Nate Begemana148d982006-01-18 22:35:16 +00007063 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007064 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007065
Nate Begeman1d4d4142005-09-01 00:19:25 +00007066 // fold (fp_round c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00007067 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007068 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelfdc40a02009-02-17 22:15:04 +00007069
Chris Lattner79dbea52006-03-13 06:26:26 +00007070 // fold (fp_round (fp_extend x)) -> x
7071 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7072 return N0.getOperand(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007073
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00007074 // fold (fp_round (fp_round x)) -> (fp_round x)
7075 if (N0.getOpcode() == ISD::FP_ROUND) {
7076 // This is a value preserving truncation if both round's are.
7077 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greifba36cb52008-08-28 21:40:38 +00007078 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickac6d9be2013-05-25 02:42:55 +00007079 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0aa5e6f2008-01-24 06:45:35 +00007080 DAG.getIntPtrConstant(IsTrunc));
7081 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007082
Chris Lattner79dbea52006-03-13 06:26:26 +00007083 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greifba36cb52008-08-28 21:40:38 +00007084 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007085 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007086 N0.getOperand(0), N1);
Gabor Greifba36cb52008-08-28 21:40:38 +00007087 AddToWorkList(Tmp.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007088 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007089 Tmp, N0.getOperand(1));
Chris Lattner79dbea52006-03-13 06:26:26 +00007090 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007091
Dan Gohman475871a2008-07-27 21:46:04 +00007092 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007093}
7094
Dan Gohman475871a2008-07-27 21:46:04 +00007095SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007097 EVT VT = N->getValueType(0);
7098 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman646d7e22005-09-02 21:18:40 +00007099 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007100
Nate Begeman1d4d4142005-09-01 00:19:25 +00007101 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner2392ae72010-04-15 04:48:01 +00007102 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohman4fbd7962008-09-12 18:08:03 +00007103 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007104 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007105 }
Bill Wendling0225a1d2009-01-30 23:15:49 +00007106
Dan Gohman475871a2008-07-27 21:46:04 +00007107 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007108}
7109
Dan Gohman475871a2008-07-27 21:46:04 +00007110SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7111 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007112 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007113 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007114
Chris Lattner5938bef2007-12-29 06:55:23 +00007115 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelfdc40a02009-02-17 22:15:04 +00007116 if (N->hasOneUse() &&
Dan Gohmane7852d02009-01-26 04:35:06 +00007117 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman475871a2008-07-27 21:46:04 +00007118 return SDValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00007119
Nate Begeman1d4d4142005-09-01 00:19:25 +00007120 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigande669c932012-10-29 18:35:49 +00007121 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007122 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner0bd48932008-01-17 07:00:52 +00007123
7124 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7125 // value of X.
Gabor Greif12632d22008-08-30 19:29:20 +00007126 if (N0.getOpcode() == ISD::FP_ROUND
7127 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +00007128 SDValue In = N0.getOperand(0);
Chris Lattner0bd48932008-01-17 07:00:52 +00007129 if (In.getValueType() == VT) return In;
Duncan Sands8e4eb092008-06-08 20:54:56 +00007130 if (VT.bitsLT(In.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00007131 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007132 In, N0.getOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00007133 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner0bd48932008-01-17 07:00:52 +00007134 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007135
Chris Lattner0bd48932008-01-17 07:00:52 +00007136 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkel03c8f8f2013-10-04 22:18:12 +00007137 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands25cf2272008-11-24 14:53:14 +00007138 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng03294662008-10-14 21:26:46 +00007139 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Cheng466685d2006-10-09 20:57:25 +00007140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007141 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0225a1d2009-01-30 23:15:49 +00007142 LN0->getChain(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007143 LN0->getBasePtr(), N0.getValueType(),
7144 LN0->getMemOperand());
Chris Lattnere564dbb2006-05-05 21:34:35 +00007145 CombineTo(N, ExtLoad);
Bill Wendling0225a1d2009-01-30 23:15:49 +00007146 CombineTo(N0.getNode(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007147 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0225a1d2009-01-30 23:15:49 +00007148 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattnere564dbb2006-05-05 21:34:35 +00007149 ExtLoad.getValue(1));
Dan Gohman475871a2008-07-27 21:46:04 +00007150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattnere564dbb2006-05-05 21:34:35 +00007151 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00007152
Dan Gohman475871a2008-07-27 21:46:04 +00007153 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007154}
7155
Dan Gohman475871a2008-07-27 21:46:04 +00007156SDValue DAGCombiner::visitFNEG(SDNode *N) {
7157 SDValue N0 = N->getOperand(0);
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007158 EVT VT = N->getValueType(0);
Nate Begemana148d982006-01-18 22:35:16 +00007159
Craig Topperdd201ff2012-09-11 01:45:21 +00007160 if (VT.isVector()) {
7161 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7162 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper956342b2012-09-09 22:58:45 +00007163 }
7164
Owen Andersonafd3d562012-03-06 00:29:31 +00007165 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7166 &DAG.getTarget().Options))
Duncan Sands25cf2272008-11-24 14:53:14 +00007167 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman23ff1822007-07-02 15:48:56 +00007168
Chris Lattner3bd39d42008-01-27 17:42:27 +00007169 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7170 // constant pool values.
Owen Anderson29f60f32012-04-02 22:10:29 +00007171 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007172 !VT.isVector() &&
7173 N0.getNode()->hasOneUse() &&
7174 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman475871a2008-07-27 21:46:04 +00007175 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007176 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00007177 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007178 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00007179 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00007180 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007181 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikov2bcf60a2009-10-20 21:37:45 +00007182 VT, Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00007183 }
7184 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007185
Owen Anderson58d57292012-09-01 06:04:27 +00007186 // (fneg (fmul c, x)) -> (fmul -c, x)
7187 if (N0.getOpcode() == ISD::FMUL) {
7188 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Hinesdce4a402014-05-29 02:49:00 -07007189 if (CFP1) {
7190 APFloat CVal = CFP1->getValueAPF();
7191 CVal.changeSign();
7192 if (Level >= AfterLegalizeDAG &&
7193 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7194 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7195 return DAG.getNode(
7196 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7197 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7198 }
Owen Anderson58d57292012-09-01 06:04:27 +00007199 }
7200
Dan Gohman475871a2008-07-27 21:46:04 +00007201 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007202}
7203
Owen Anderson7c626d32012-08-13 23:32:49 +00007204SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7205 SDValue N0 = N->getOperand(0);
7206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207 EVT VT = N->getValueType(0);
7208
7209 // fold (fceil c1) -> fceil(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007210 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007211 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007212
7213 return SDValue();
7214}
7215
7216SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7217 SDValue N0 = N->getOperand(0);
7218 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7219 EVT VT = N->getValueType(0);
7220
7221 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007222 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007223 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007224
7225 return SDValue();
7226}
7227
7228SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7229 SDValue N0 = N->getOperand(0);
7230 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7231 EVT VT = N->getValueType(0);
7232
7233 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007234 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007235 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Anderson7c626d32012-08-13 23:32:49 +00007236
7237 return SDValue();
7238}
7239
Dan Gohman475871a2008-07-27 21:46:04 +00007240SDValue DAGCombiner::visitFABS(SDNode *N) {
7241 SDValue N0 = N->getOperand(0);
Nate Begemana148d982006-01-18 22:35:16 +00007242 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Andersone50ed302009-08-10 22:56:29 +00007243 EVT VT = N->getValueType(0);
Scott Michelfdc40a02009-02-17 22:15:04 +00007244
Craig Topperdd201ff2012-09-11 01:45:21 +00007245 if (VT.isVector()) {
7246 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7247 if (FoldedVOp.getNode()) return FoldedVOp;
7248 }
7249
Nate Begeman1d4d4142005-09-01 00:19:25 +00007250 // fold (fabs c1) -> fabs(c1)
Ulrich Weigande669c932012-10-29 18:35:49 +00007251 if (N0CFP)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007252 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007253 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00007254 if (N0.getOpcode() == ISD::FABS)
Nate Begeman83e75ec2005-09-06 04:43:02 +00007255 return N->getOperand(0);
Nate Begeman1d4d4142005-09-01 00:19:25 +00007256 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner12d83032006-03-05 05:30:57 +00007257 // fold (fabs (fcopysign x, y)) -> (fabs x)
7258 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007259 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00007260
Chris Lattner3bd39d42008-01-27 17:42:27 +00007261 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7262 // constant pool values.
Stephen Lin155615d2013-07-08 00:37:03 +00007263 if (!TLI.isFAbsFree(VT) &&
Owen Anderson29f60f32012-04-02 22:10:29 +00007264 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands83ec4b62008-06-06 12:08:01 +00007265 N0.getOperand(0).getValueType().isInteger() &&
7266 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman475871a2008-07-27 21:46:04 +00007267 SDValue Int = N0.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00007268 EVT IntVT = Int.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00007269 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007270 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +00007271 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greifba36cb52008-08-28 21:40:38 +00007272 AddToWorkList(Int.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007273 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007274 N->getValueType(0), Int);
Chris Lattner3bd39d42008-01-27 17:42:27 +00007275 }
7276 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007277
Dan Gohman475871a2008-07-27 21:46:04 +00007278 return SDValue();
Nate Begeman1d4d4142005-09-01 00:19:25 +00007279}
7280
Dan Gohman475871a2008-07-27 21:46:04 +00007281SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7282 SDValue Chain = N->getOperand(0);
7283 SDValue N1 = N->getOperand(1);
7284 SDValue N2 = N->getOperand(2);
Scott Michelfdc40a02009-02-17 22:15:04 +00007285
Dan Gohmane0f06c72009-11-17 00:47:23 +00007286 // If N is a constant we could fold this into a fallthrough or unconditional
7287 // branch. However that doesn't happen very often in normal code, because
7288 // Instcombine/SimplifyCFG should have handled the available opportunities.
7289 // If we did this folding here, it would be necessary to update the
7290 // MachineBasicBlock CFG, which is awkward.
7291
Nate Begeman750ac1b2006-02-01 07:19:44 +00007292 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7293 // on the target.
Scott Michelfdc40a02009-02-17 22:15:04 +00007294 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellard3ef53832013-03-08 15:36:57 +00007295 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7296 N1.getOperand(0).getValueType())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007297 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00007298 Chain, N1.getOperand(2),
Nate Begeman750ac1b2006-02-01 07:19:44 +00007299 N1.getOperand(0), N1.getOperand(1), N2);
7300 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007301
Evan Cheng2a135ae2010-10-04 22:41:01 +00007302 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7303 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7304 (N1.getOperand(0).hasOneUse() &&
7305 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07007306 SDNode *Trunc = nullptr;
Evan Cheng2a135ae2010-10-04 22:41:01 +00007307 if (N1.getOpcode() == ISD::TRUNCATE) {
7308 // Look pass the truncate.
7309 Trunc = N1.getNode();
7310 N1 = N1.getOperand(0);
7311 }
Evan Chengd40d03e2010-01-06 19:38:29 +00007312
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007313 // Match this pattern so that we can generate simpler code:
7314 //
7315 // %a = ...
7316 // %b = and i32 %a, 2
7317 // %c = srl i32 %b, 1
7318 // brcond i32 %c ...
7319 //
7320 // into
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007321 //
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007322 // %a = ...
Evan Chengd40d03e2010-01-06 19:38:29 +00007323 // %b = and i32 %a, 2
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007324 // %c = setcc eq %b, 0
7325 // brcond %c ...
7326 //
7327 // This applies only when the AND constant value has one bit set and the
7328 // SRL constant is equal to the log2 of the AND constant. The back-end is
7329 // smart enough to convert the result into a TEST/JMP sequence.
7330 SDValue Op0 = N1.getOperand(0);
7331 SDValue Op1 = N1.getOperand(1);
7332
7333 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007334 Op1.getOpcode() == ISD::Constant) {
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007335 SDValue AndOp1 = Op0.getOperand(1);
7336
7337 if (AndOp1.getOpcode() == ISD::Constant) {
7338 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7339
7340 if (AndConst.isPowerOf2() &&
7341 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7342 SDValue SetCC =
Andrew Trickac6d9be2013-05-25 02:42:55 +00007343 DAG.getSetCC(SDLoc(N),
Matt Arsenault225ed702013-05-18 00:21:46 +00007344 getSetCCResultType(Op0.getValueType()),
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007345 Op0, DAG.getConstant(0, Op0.getValueType()),
7346 ISD::SETNE);
7347
Andrew Trickac6d9be2013-05-25 02:42:55 +00007348 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Chengd40d03e2010-01-06 19:38:29 +00007349 MVT::Other, Chain, SetCC, N2);
7350 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7351 // will convert it back to (X & C1) >> C2.
7352 CombineTo(N, NewBRCond, false);
7353 // Truncate is dead.
7354 if (Trunc) {
7355 removeFromWorkList(Trunc);
7356 DAG.DeleteNode(Trunc);
7357 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007358 // Replace the uses of SRL with SETCC
Evan Cheng2c755ba2010-02-27 07:36:59 +00007359 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007360 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007361 removeFromWorkList(N1.getNode());
7362 DAG.DeleteNode(N1.getNode());
Evan Chengd40d03e2010-01-06 19:38:29 +00007363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007364 }
7365 }
7366 }
Evan Cheng2a135ae2010-10-04 22:41:01 +00007367
7368 if (Trunc)
7369 // Restore N1 if the above transformation doesn't match.
7370 N1 = N->getOperand(1);
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007371 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007372
Evan Cheng2c755ba2010-02-27 07:36:59 +00007373 // Transform br(xor(x, y)) -> br(x != y)
7374 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7375 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7376 SDNode *TheXor = N1.getNode();
7377 SDValue Op0 = TheXor->getOperand(0);
7378 SDValue Op1 = TheXor->getOperand(1);
7379 if (Op0.getOpcode() == Op1.getOpcode()) {
7380 // Avoid missing important xor optimizations.
7381 SDValue Tmp = visitXOR(TheXor);
Evan Cheng78ec0252013-01-09 20:56:40 +00007382 if (Tmp.getNode()) {
7383 if (Tmp.getNode() != TheXor) {
7384 DEBUG(dbgs() << "\nReplacing.8 ";
7385 TheXor->dump(&DAG);
7386 dbgs() << "\nWith: ";
7387 Tmp.getNode()->dump(&DAG);
7388 dbgs() << '\n');
7389 WorkListRemover DeadNodes(*this);
7390 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7391 removeFromWorkList(TheXor);
7392 DAG.DeleteNode(TheXor);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007393 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng78ec0252013-01-09 20:56:40 +00007394 MVT::Other, Chain, Tmp, N2);
7395 }
7396
Benjamin Kramer0b68b752013-03-30 21:28:18 +00007397 // visitXOR has changed XOR's operands or replaced the XOR completely,
7398 // bail out.
7399 return SDValue(N, 0);
Evan Cheng2c755ba2010-02-27 07:36:59 +00007400 }
7401 }
7402
7403 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7404 bool Equal = false;
7405 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7406 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7407 Op0.getOpcode() == ISD::XOR) {
7408 TheXor = Op0.getNode();
7409 Equal = true;
7410 }
7411
Evan Cheng2a135ae2010-10-04 22:41:01 +00007412 EVT SetCCVT = N1.getValueType();
Evan Cheng2c755ba2010-02-27 07:36:59 +00007413 if (LegalTypes)
Matt Arsenault225ed702013-05-18 00:21:46 +00007414 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00007415 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007416 SetCCVT,
7417 Op0, Op1,
7418 Equal ? ISD::SETEQ : ISD::SETNE);
7419 // Replace the uses of XOR with SETCC
7420 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007421 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Cheng2a135ae2010-10-04 22:41:01 +00007422 removeFromWorkList(N1.getNode());
7423 DAG.DeleteNode(N1.getNode());
Andrew Trickac6d9be2013-05-25 02:42:55 +00007424 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng2c755ba2010-02-27 07:36:59 +00007425 MVT::Other, Chain, SetCC, N2);
7426 }
7427 }
Bill Wendlinga02a3dd2009-03-26 06:14:09 +00007428
Dan Gohman475871a2008-07-27 21:46:04 +00007429 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007430}
7431
Chris Lattner3ea0b472005-10-05 06:47:48 +00007432// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7433//
Dan Gohman475871a2008-07-27 21:46:04 +00007434SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattner3ea0b472005-10-05 06:47:48 +00007435 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman475871a2008-07-27 21:46:04 +00007436 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelfdc40a02009-02-17 22:15:04 +00007437
Dan Gohmane0f06c72009-11-17 00:47:23 +00007438 // If N is a constant we could fold this into a fallthrough or unconditional
7439 // branch. However that doesn't happen very often in normal code, because
7440 // Instcombine/SimplifyCFG should have handled the available opportunities.
7441 // If we did this folding here, it would be necessary to update the
7442 // MachineBasicBlock CFG, which is awkward.
7443
Duncan Sands8eab8a22008-06-09 11:32:28 +00007444 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault225ed702013-05-18 00:21:46 +00007445 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00007446 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenff97d4f2009-02-03 00:47:48 +00007447 false);
Gabor Greifba36cb52008-08-28 21:40:38 +00007448 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner30f73e72006-10-14 03:52:46 +00007449
Nate Begemane17daeb2005-10-05 21:43:42 +00007450 // fold to a simpler setcc
Gabor Greifba36cb52008-08-28 21:40:38 +00007451 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007452 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendlingc0debad2009-01-30 23:27:35 +00007453 N->getOperand(0), Simp.getOperand(2),
7454 Simp.getOperand(0), Simp.getOperand(1),
7455 N->getOperand(4));
7456
Dan Gohman475871a2008-07-27 21:46:04 +00007457 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +00007458}
7459
Evan Chengc4b527a2012-01-13 01:37:24 +00007460/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7461/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng03be3622012-03-06 23:33:32 +00007462/// addressing mode.
Evan Chengc4b527a2012-01-13 01:37:24 +00007463static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7464 SelectionDAG &DAG,
7465 const TargetLowering &TLI) {
7466 EVT VT;
7467 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7468 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7469 return false;
7470 VT = Use->getValueType(0);
7471 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7472 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7473 return false;
7474 VT = ST->getValue().getValueType();
7475 } else
7476 return false;
7477
Chandler Carruth56d433d2013-01-07 15:14:13 +00007478 TargetLowering::AddrMode AM;
Evan Chengc4b527a2012-01-13 01:37:24 +00007479 if (N->getOpcode() == ISD::ADD) {
7480 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7481 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007482 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007483 AM.BaseOffs = Offset->getSExtValue();
7484 else
Evan Cheng03be3622012-03-06 23:33:32 +00007485 // [reg +/- reg]
7486 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007487 } else if (N->getOpcode() == ISD::SUB) {
7488 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7489 if (Offset)
Evan Cheng03be3622012-03-06 23:33:32 +00007490 // [reg +/- imm]
Evan Chengc4b527a2012-01-13 01:37:24 +00007491 AM.BaseOffs = -Offset->getSExtValue();
7492 else
Evan Cheng03be3622012-03-06 23:33:32 +00007493 // [reg +/- reg]
7494 AM.Scale = 1;
Evan Chengc4b527a2012-01-13 01:37:24 +00007495 } else
7496 return false;
7497
7498 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7499}
7500
Duncan Sandsec87aa82008-06-15 20:12:31 +00007501/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7502/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattner448f2192006-11-11 00:39:41 +00007503/// and it has other uses besides the load / store. After the
7504/// transformation, the new indexed load / store has effectively folded
7505/// the add / subtract in and all of its other uses are redirected to the
7506/// new load / store.
7507bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007508 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007509 return false;
7510
7511 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007512 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007513 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007514 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007515 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007516 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007517 VT = LD->getMemoryVT();
Evan Cheng83060c52007-03-07 08:07:03 +00007518 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattner448f2192006-11-11 00:39:41 +00007519 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7520 return false;
7521 Ptr = LD->getBasePtr();
7522 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007523 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007524 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007525 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007526 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7527 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7528 return false;
7529 Ptr = ST->getBasePtr();
7530 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007531 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007532 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007533 }
Chris Lattner448f2192006-11-11 00:39:41 +00007534
Chris Lattner9f1794e2006-11-11 00:56:29 +00007535 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7536 // out. There is no reason to make this a preinc/predec.
7537 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greifba36cb52008-08-28 21:40:38 +00007538 Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007539 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007540
Chris Lattner9f1794e2006-11-11 00:56:29 +00007541 // Ask the target to do addressing mode selection.
Dan Gohman475871a2008-07-27 21:46:04 +00007542 SDValue BasePtr;
7543 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007544 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7545 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7546 return false;
Hal Finkel089a5f82013-02-08 21:35:47 +00007547
7548 // Backends without true r+i pre-indexed forms may need to pass a
7549 // constant base with a variable offset so that constant coercion
7550 // will work with the patterns in canonical form.
7551 bool Swapped = false;
7552 if (isa<ConstantSDNode>(BasePtr)) {
7553 std::swap(BasePtr, Offset);
7554 Swapped = true;
7555 }
7556
Evan Chenga7d4a042007-05-03 23:52:19 +00007557 // Don't create a indexed load / store with zero offset.
7558 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007559 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007560 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007561
Chris Lattner41e53fd2006-11-11 01:00:15 +00007562 // Try turning it into a pre-indexed load / store except when:
Evan Chengc843abe2007-05-24 02:35:39 +00007563 // 1) The new base ptr is a frame index.
7564 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattner9f1794e2006-11-11 00:56:29 +00007565 // predecessor of the value being stored.
Evan Chengc843abe2007-05-24 02:35:39 +00007566 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattner9f1794e2006-11-11 00:56:29 +00007567 // that would create a cycle.
Evan Chengc843abe2007-05-24 02:35:39 +00007568 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattner448f2192006-11-11 00:39:41 +00007569
Chris Lattner41e53fd2006-11-11 01:00:15 +00007570 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7571 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcaab1292009-05-06 18:25:01 +00007572 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattner41e53fd2006-11-11 01:00:15 +00007573 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007574
Chris Lattner41e53fd2006-11-11 01:00:15 +00007575 // Check #2.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007576 if (!isLoad) {
Dan Gohman475871a2008-07-27 21:46:04 +00007577 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greifba36cb52008-08-28 21:40:38 +00007578 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007579 return false;
Chris Lattner448f2192006-11-11 00:39:41 +00007580 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007581
Hal Finkel089a5f82013-02-08 21:35:47 +00007582 // If the offset is a constant, there may be other adds of constants that
7583 // can be folded with this one. We should do this to avoid having to keep
7584 // a copy of the original base pointer.
7585 SmallVector<SDNode *, 16> OtherUses;
7586 if (isa<ConstantSDNode>(Offset))
Stephen Hinesdce4a402014-05-29 02:49:00 -07007587 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel089a5f82013-02-08 21:35:47 +00007588 if (Use == Ptr.getNode())
7589 continue;
7590
7591 if (Use->isPredecessorOf(N))
7592 continue;
7593
7594 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7595 OtherUses.clear();
7596 break;
7597 }
7598
7599 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600 if (Op1.getNode() == BasePtr.getNode())
7601 std::swap(Op0, Op1);
7602 assert(Op0.getNode() == BasePtr.getNode() &&
7603 "Use of ADD/SUB but not an operand");
7604
7605 if (!isa<ConstantSDNode>(Op1)) {
7606 OtherUses.clear();
7607 break;
7608 }
7609
7610 // FIXME: In some cases, we can be smarter about this.
7611 if (Op1.getValueType() != Offset.getValueType()) {
7612 OtherUses.clear();
7613 break;
7614 }
7615
7616 OtherUses.push_back(Use);
7617 }
7618
7619 if (Swapped)
7620 std::swap(BasePtr, Offset);
7621
Evan Chengc843abe2007-05-24 02:35:39 +00007622 // Now check for #3 and #4.
Chris Lattner9f1794e2006-11-11 00:56:29 +00007623 bool RealUse = false;
Lang Hames944520f2011-07-07 04:31:51 +00007624
7625 // Caches for hasPredecessorHelper
7626 SmallPtrSet<const SDNode *, 32> Visited;
7627 SmallVector<const SDNode *, 16> Worklist;
7628
Stephen Hinesdce4a402014-05-29 02:49:00 -07007629 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattner9f1794e2006-11-11 00:56:29 +00007630 if (Use == N)
7631 continue;
Lang Hames944520f2011-07-07 04:31:51 +00007632 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007633 return false;
7634
Evan Chengc4b527a2012-01-13 01:37:24 +00007635 // If Ptr may be folded in addressing mode of other use, then it's
7636 // not profitable to do this transformation.
7637 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007638 RealUse = true;
7639 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007640
Chris Lattner9f1794e2006-11-11 00:56:29 +00007641 if (!RealUse)
7642 return false;
7643
Dan Gohman475871a2008-07-27 21:46:04 +00007644 SDValue Result;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007645 if (isLoad)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007646 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007647 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007648 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00007649 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007650 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007651 ++PreIndexedNodes;
7652 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007653 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007654 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007655 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007656 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007657 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007658 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007659 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007660 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7661 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007662 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007663 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007664 }
7665
Chris Lattner9f1794e2006-11-11 00:56:29 +00007666 // Finally, since the node is now dead, remove it from the graph.
7667 DAG.DeleteNode(N);
7668
Hal Finkel089a5f82013-02-08 21:35:47 +00007669 if (Swapped)
7670 std::swap(BasePtr, Offset);
7671
7672 // Replace other uses of BasePtr that can be updated to use Ptr
7673 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7674 unsigned OffsetIdx = 1;
7675 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7676 OffsetIdx = 0;
7677 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7678 BasePtr.getNode() && "Expected BasePtr operand");
7679
Silviu Baranga730a5702013-04-26 15:52:24 +00007680 // We need to replace ptr0 in the following expression:
7681 // x0 * offset0 + y0 * ptr0 = t0
7682 // knowing that
7683 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lin155615d2013-07-08 00:37:03 +00007684 //
Silviu Baranga730a5702013-04-26 15:52:24 +00007685 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7686 // indexed load/store and the expresion that needs to be re-written.
7687 //
7688 // Therefore, we have:
7689 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel089a5f82013-02-08 21:35:47 +00007690
7691 ConstantSDNode *CN =
7692 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Baranga730a5702013-04-26 15:52:24 +00007693 int X0, X1, Y0, Y1;
7694 APInt Offset0 = CN->getAPIntValue();
7695 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel089a5f82013-02-08 21:35:47 +00007696
Silviu Baranga730a5702013-04-26 15:52:24 +00007697 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7698 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7699 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7700 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel089a5f82013-02-08 21:35:47 +00007701
Silviu Baranga730a5702013-04-26 15:52:24 +00007702 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7703
7704 APInt CNV = Offset0;
7705 if (X0 < 0) CNV = -CNV;
7706 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7707 else CNV = CNV - Offset1;
7708
7709 // We can now generate the new expression.
7710 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7711 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7712
7713 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickac6d9be2013-05-25 02:42:55 +00007714 SDLoc(OtherUses[i]),
Hal Finkel089a5f82013-02-08 21:35:47 +00007715 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7716 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7717 removeFromWorkList(OtherUses[i]);
7718 DAG.DeleteNode(OtherUses[i]);
7719 }
7720
Chris Lattner9f1794e2006-11-11 00:56:29 +00007721 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007722 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greifba36cb52008-08-28 21:40:38 +00007723 removeFromWorkList(Ptr.getNode());
7724 DAG.DeleteNode(Ptr.getNode());
Chris Lattner9f1794e2006-11-11 00:56:29 +00007725
7726 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007727}
7728
Duncan Sandsec87aa82008-06-15 20:12:31 +00007729/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattner448f2192006-11-11 00:39:41 +00007730/// add / sub of the base pointer node into a post-indexed load / store.
7731/// The transformation folded the add / subtract into the new indexed
7732/// load / store effectively and all of its uses are redirected to the
7733/// new load / store.
7734bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman50185242011-11-12 00:35:34 +00007735 if (Level < AfterLegalizeDAG)
Chris Lattner448f2192006-11-11 00:39:41 +00007736 return false;
7737
7738 bool isLoad = true;
Dan Gohman475871a2008-07-27 21:46:04 +00007739 SDValue Ptr;
Owen Andersone50ed302009-08-10 22:56:29 +00007740 EVT VT;
Chris Lattner448f2192006-11-11 00:39:41 +00007741 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007742 if (LD->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007743 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007744 VT = LD->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007745 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7746 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7747 return false;
7748 Ptr = LD->getBasePtr();
7749 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattnerddf89562008-01-17 19:59:44 +00007750 if (ST->isIndexed())
Evan Chenge90460e2006-12-16 06:25:23 +00007751 return false;
Dan Gohmanb625f2f2008-01-30 00:15:11 +00007752 VT = ST->getMemoryVT();
Chris Lattner448f2192006-11-11 00:39:41 +00007753 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7754 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7755 return false;
7756 Ptr = ST->getBasePtr();
7757 isLoad = false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007758 } else {
Chris Lattner448f2192006-11-11 00:39:41 +00007759 return false;
Bill Wendlingc0debad2009-01-30 23:27:35 +00007760 }
Chris Lattner448f2192006-11-11 00:39:41 +00007761
Gabor Greifba36cb52008-08-28 21:40:38 +00007762 if (Ptr.getNode()->hasOneUse())
Chris Lattner9f1794e2006-11-11 00:56:29 +00007763 return false;
Scott Michelfdc40a02009-02-17 22:15:04 +00007764
Stephen Hinesdce4a402014-05-29 02:49:00 -07007765 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattner9f1794e2006-11-11 00:56:29 +00007766 if (Op == N ||
7767 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7768 continue;
7769
Dan Gohman475871a2008-07-27 21:46:04 +00007770 SDValue BasePtr;
7771 SDValue Offset;
Chris Lattner9f1794e2006-11-11 00:56:29 +00007772 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7773 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Chenga7d4a042007-05-03 23:52:19 +00007774 // Don't create a indexed load / store with zero offset.
7775 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman002e5d02008-03-13 22:13:53 +00007776 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Chenga7d4a042007-05-03 23:52:19 +00007777 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007778
Chris Lattner9f1794e2006-11-11 00:56:29 +00007779 // Try turning it into a post-indexed load / store except when
Evan Chengc4b527a2012-01-13 01:37:24 +00007780 // 1) All uses are load / store ops that use it as base ptr (and
7781 // it may be folded as addressing mmode).
Chris Lattner9f1794e2006-11-11 00:56:29 +00007782 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7783 // nor a successor of N. Otherwise, if Op is folded that would
7784 // create a cycle.
7785
Evan Chengcaab1292009-05-06 18:25:01 +00007786 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7787 continue;
7788
Chris Lattner9f1794e2006-11-11 00:56:29 +00007789 // Check for #1.
7790 bool TryNext = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -07007791 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00007792 if (Use == Ptr.getNode())
Chris Lattner448f2192006-11-11 00:39:41 +00007793 continue;
7794
Chris Lattner9f1794e2006-11-11 00:56:29 +00007795 // If all the uses are load / store addresses, then don't do the
7796 // transformation.
7797 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7798 bool RealUse = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -07007799 for (SDNode *UseUse : Use->uses()) {
Stephen Lin155615d2013-07-08 00:37:03 +00007800 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattner9f1794e2006-11-11 00:56:29 +00007801 RealUse = true;
7802 }
Chris Lattner448f2192006-11-11 00:39:41 +00007803
Chris Lattner9f1794e2006-11-11 00:56:29 +00007804 if (!RealUse) {
7805 TryNext = true;
7806 break;
Chris Lattner448f2192006-11-11 00:39:41 +00007807 }
7808 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007809 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007810
Chris Lattner9f1794e2006-11-11 00:56:29 +00007811 if (TryNext)
7812 continue;
Chris Lattner448f2192006-11-11 00:39:41 +00007813
Chris Lattner9f1794e2006-11-11 00:56:29 +00007814 // Check for #2
Evan Cheng917be682008-03-04 00:41:45 +00007815 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman475871a2008-07-27 21:46:04 +00007816 SDValue Result = isLoad
Andrew Trickac6d9be2013-05-25 02:42:55 +00007817 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007818 BasePtr, Offset, AM)
Andrew Trickac6d9be2013-05-25 02:42:55 +00007819 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendlingc0debad2009-01-30 23:27:35 +00007820 BasePtr, Offset, AM);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007821 ++PostIndexedNodes;
7822 ++NodesCombined;
David Greenef1090292010-01-05 01:25:00 +00007823 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007824 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007825 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007826 Result.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007827 dbgs() << '\n');
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007828 WorkListRemover DeadNodes(*this);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007829 if (isLoad) {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007830 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7831 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007832 } else {
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007833 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattner448f2192006-11-11 00:39:41 +00007834 }
Chris Lattner9f1794e2006-11-11 00:56:29 +00007835
Chris Lattner9f1794e2006-11-11 00:56:29 +00007836 // Finally, since the node is now dead, remove it from the graph.
7837 DAG.DeleteNode(N);
7838
7839 // Replace the uses of Use with uses of the updated base value.
Dan Gohman475871a2008-07-27 21:46:04 +00007840 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007841 Result.getValue(isLoad ? 1 : 0));
Chris Lattner9f1794e2006-11-11 00:56:29 +00007842 removeFromWorkList(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007843 DAG.DeleteNode(Op);
Chris Lattner9f1794e2006-11-11 00:56:29 +00007844 return true;
Chris Lattner448f2192006-11-11 00:39:41 +00007845 }
7846 }
7847 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007848
Chris Lattner448f2192006-11-11 00:39:41 +00007849 return false;
7850}
7851
Stephen Hinesdce4a402014-05-29 02:49:00 -07007852/// \brief Return the base-pointer arithmetic from an indexed \p LD.
7853SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
7854 ISD::MemIndexedMode AM = LD->getAddressingMode();
7855 assert(AM != ISD::UNINDEXED);
7856 SDValue BP = LD->getOperand(1);
7857 SDValue Inc = LD->getOperand(2);
7858 unsigned Opc =
7859 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
7860 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
7861}
7862
Dan Gohman475871a2008-07-27 21:46:04 +00007863SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Cheng466685d2006-10-09 20:57:25 +00007864 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007865 SDValue Chain = LD->getChain();
7866 SDValue Ptr = LD->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00007867
Evan Cheng45a7ca92007-05-01 00:38:21 +00007868 // If load is not volatile and there are no uses of the loaded value (and
7869 // the updated indexed value in case of indexed loads), change uses of the
7870 // chain value into uses of the chain input (i.e. delete the dead load).
7871 if (!LD->isVolatile()) {
Owen Anderson825b72b2009-08-11 20:47:22 +00007872 if (N->getValueType(1) == MVT::Other) {
Evan Cheng498f5592007-05-01 08:53:39 +00007873 // Unindexed loads.
Craig Topper704e1a02012-01-07 18:31:09 +00007874 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng02c42852008-01-16 23:11:54 +00007875 // It's not safe to use the two value CombineTo variant here. e.g.
7876 // v1, chain2 = load chain1, loc
7877 // v2, chain3 = load chain2, loc
7878 // v3 = add v2, c
Chris Lattner125991a2008-01-24 07:57:06 +00007879 // Now we replace use of chain2 with chain1. This makes the second load
7880 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenef1090292010-01-05 01:25:00 +00007881 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007882 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007883 dbgs() << "\nWith chain: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007884 Chain.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007885 dbgs() << "\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007886 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendlingc0debad2009-01-30 23:27:35 +00007888
Chris Lattner125991a2008-01-24 07:57:06 +00007889 if (N->use_empty()) {
7890 removeFromWorkList(N);
7891 DAG.DeleteNode(N);
7892 }
Bill Wendlingc0debad2009-01-30 23:27:35 +00007893
Dan Gohman475871a2008-07-27 21:46:04 +00007894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng02c42852008-01-16 23:11:54 +00007895 }
Evan Cheng498f5592007-05-01 08:53:39 +00007896 } else {
7897 // Indexed loads.
Owen Anderson825b72b2009-08-11 20:47:22 +00007898 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Stephen Hinesdce4a402014-05-29 02:49:00 -07007899 if (!N->hasAnyUseOfValue(0)) {
Dale Johannesene8d72302009-02-06 23:05:02 +00007900 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Stephen Hinesdce4a402014-05-29 02:49:00 -07007901 SDValue Index;
7902 if (N->hasAnyUseOfValue(1)) {
7903 Index = SplitIndexingFromLoad(LD);
7904 // Try to fold the base pointer arithmetic into subsequent loads and
7905 // stores.
7906 AddUsersToWorkList(N);
7907 } else
7908 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng2c755ba2010-02-27 07:36:59 +00007909 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007910 N->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007911 dbgs() << "\nWith: ";
Chris Lattnerbbbfa992009-08-23 06:35:02 +00007912 Undef.getNode()->dump(&DAG);
David Greenef1090292010-01-05 01:25:00 +00007913 dbgs() << " and 2 other values\n");
Chris Lattnerf8dc0612008-02-03 06:49:24 +00007914 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007915 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Stephen Hinesdce4a402014-05-29 02:49:00 -07007916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00007917 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng02c42852008-01-16 23:11:54 +00007918 removeFromWorkList(N);
Evan Cheng02c42852008-01-16 23:11:54 +00007919 DAG.DeleteNode(N);
Dan Gohman475871a2008-07-27 21:46:04 +00007920 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng45a7ca92007-05-01 00:38:21 +00007921 }
Evan Cheng45a7ca92007-05-01 00:38:21 +00007922 }
7923 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007924
Chris Lattner01a22022005-10-10 22:04:48 +00007925 // If this load is directly stored, replace the load value with the stored
7926 // value.
7927 // TODO: Handle store large -> read small portion.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007928 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Cheng9ef82ce2011-03-11 00:48:56 +00007929 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greifba36cb52008-08-28 21:40:38 +00007930 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00007931 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7932 if (PrevST->getBasePtr() == Ptr &&
7933 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007934 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Cheng8b2794a2006-10-13 21:14:26 +00007935 }
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007936 }
Scott Michelfdc40a02009-02-17 22:15:04 +00007937
Evan Cheng255f20f2010-04-01 06:04:33 +00007938 // Try to infer better alignment information than the load already has.
7939 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00007940 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonb48783b2013-02-05 19:24:39 +00007941 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7942 SDValue NewLoad =
Andrew Trickac6d9be2013-05-25 02:42:55 +00007943 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Chenged1c0c72011-11-28 22:37:34 +00007944 LD->getValueType(0),
7945 Chain, Ptr, LD->getPointerInfo(),
7946 LD->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007947 LD->isVolatile(), LD->isNonTemporal(), Align,
7948 LD->getTBAAInfo());
Owen Andersonb48783b2013-02-05 19:24:39 +00007949 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7950 }
Evan Cheng255f20f2010-04-01 06:04:33 +00007951 }
7952 }
7953
Hal Finkel253acef2013-08-29 03:29:55 +00007954 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7955 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -07007956#ifndef NDEBUG
7957 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7958 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7959 UseAA = false;
7960#endif
7961 if (UseAA && LD->isUnindexed()) {
Jim Laskey279f0532006-09-25 16:29:54 +00007962 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00007963 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00007964
Jim Laskey6ff23e52006-10-04 16:53:27 +00007965 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00007966 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00007967 SDValue ReplLoad;
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007968
Jim Laskey279f0532006-09-25 16:29:54 +00007969 // Replace the chain to void dependency.
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007970 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007971 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007972 BetterChain, Ptr, LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007973 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00007974 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastingsa9011292011-02-16 16:23:55 +00007975 LD->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00007976 BetterChain, Ptr, LD->getMemoryVT(),
7977 LD->getMemOperand());
Jim Laskeyc2b19f32006-10-11 17:47:52 +00007978 }
Jim Laskey279f0532006-09-25 16:29:54 +00007979
Jim Laskey6ff23e52006-10-04 16:53:27 +00007980 // Create token factor to keep old chain connected.
Andrew Trickac6d9be2013-05-25 02:42:55 +00007981 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00007982 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007983
Nate Begemanb6aef5c2009-09-15 00:18:30 +00007984 // Make sure the new and old chains are cleaned up.
7985 AddToWorkList(Token.getNode());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00007986
Jim Laskey274062c2006-10-13 23:32:28 +00007987 // Replace uses with load result and token factor. Don't add users
7988 // to work list.
7989 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00007990 }
7991 }
7992
Evan Cheng7fc033a2006-11-03 03:06:21 +00007993 // Try transforming N to an indexed load.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00007994 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00007995 return SDValue(N, 0);
Evan Cheng7fc033a2006-11-03 03:06:21 +00007996
Quentin Colombet83f743a2013-10-11 18:29:42 +00007997 // Try to slice up N to more direct loads if the slices are mapped to
7998 // different register banks or pairing can take place.
7999 if (SliceUpLoad(N))
8000 return SDValue(N, 0);
8001
Dan Gohman475871a2008-07-27 21:46:04 +00008002 return SDValue();
Chris Lattner01a22022005-10-10 22:04:48 +00008003}
8004
Quentin Colombet83f743a2013-10-11 18:29:42 +00008005namespace {
8006/// \brief Helper structure used to slice a load in smaller loads.
8007/// Basically a slice is obtained from the following sequence:
8008/// Origin = load Ty1, Base
8009/// Shift = srl Ty1 Origin, CstTy Amount
8010/// Inst = trunc Shift to Ty2
8011///
8012/// Then, it will be rewriten into:
8013/// Slice = load SliceTy, Base + SliceOffset
8014/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8015///
8016/// SliceTy is deduced from the number of bits that are actually used to
8017/// build Inst.
8018struct LoadedSlice {
8019 /// \brief Helper structure used to compute the cost of a slice.
8020 struct Cost {
8021 /// Are we optimizing for code size.
8022 bool ForCodeSize;
8023 /// Various cost.
8024 unsigned Loads;
8025 unsigned Truncates;
8026 unsigned CrossRegisterBanksCopies;
8027 unsigned ZExts;
8028 unsigned Shift;
8029
8030 Cost(bool ForCodeSize = false)
8031 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8032 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8033
8034 /// \brief Get the cost of one isolated slice.
8035 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8036 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8037 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8038 EVT TruncType = LS.Inst->getValueType(0);
8039 EVT LoadedType = LS.getLoadedType();
8040 if (TruncType != LoadedType &&
8041 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8042 ZExts = 1;
8043 }
8044
8045 /// \brief Account for slicing gain in the current cost.
8046 /// Slicing provide a few gains like removing a shift or a
8047 /// truncate. This method allows to grow the cost of the original
8048 /// load with the gain from this slice.
8049 void addSliceGain(const LoadedSlice &LS) {
8050 // Each slice saves a truncate.
8051 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8052 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8053 LS.Inst->getOperand(0).getValueType()))
8054 ++Truncates;
8055 // If there is a shift amount, this slice gets rid of it.
8056 if (LS.Shift)
8057 ++Shift;
8058 // If this slice can merge a cross register bank copy, account for it.
8059 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8060 ++CrossRegisterBanksCopies;
8061 }
8062
8063 Cost &operator+=(const Cost &RHS) {
8064 Loads += RHS.Loads;
8065 Truncates += RHS.Truncates;
8066 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8067 ZExts += RHS.ZExts;
8068 Shift += RHS.Shift;
8069 return *this;
8070 }
8071
8072 bool operator==(const Cost &RHS) const {
8073 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8074 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8075 ZExts == RHS.ZExts && Shift == RHS.Shift;
8076 }
8077
8078 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8079
8080 bool operator<(const Cost &RHS) const {
8081 // Assume cross register banks copies are as expensive as loads.
8082 // FIXME: Do we want some more target hooks?
8083 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8084 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8085 // Unless we are optimizing for code size, consider the
8086 // expensive operation first.
8087 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8088 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8089 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8090 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8091 }
8092
8093 bool operator>(const Cost &RHS) const { return RHS < *this; }
8094
8095 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8096
8097 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8098 };
8099 // The last instruction that represent the slice. This should be a
8100 // truncate instruction.
8101 SDNode *Inst;
8102 // The original load instruction.
8103 LoadSDNode *Origin;
8104 // The right shift amount in bits from the original load.
8105 unsigned Shift;
8106 // The DAG from which Origin came from.
8107 // This is used to get some contextual information about legal types, etc.
8108 SelectionDAG *DAG;
8109
Stephen Hinesdce4a402014-05-29 02:49:00 -07008110 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8111 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombet83f743a2013-10-11 18:29:42 +00008112 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8113
8114 LoadedSlice(const LoadedSlice &LS)
8115 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8116
8117 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8118 /// \return Result is \p BitWidth and has used bits set to 1 and
8119 /// not used bits set to 0.
8120 APInt getUsedBits() const {
8121 // Reproduce the trunc(lshr) sequence:
8122 // - Start from the truncated value.
8123 // - Zero extend to the desired bit width.
8124 // - Shift left.
8125 assert(Origin && "No original load to compare against.");
8126 unsigned BitWidth = Origin->getValueSizeInBits(0);
8127 assert(Inst && "This slice is not bound to an instruction");
8128 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8129 "Extracted slice is bigger than the whole type!");
8130 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8131 UsedBits.setAllBits();
8132 UsedBits = UsedBits.zext(BitWidth);
8133 UsedBits <<= Shift;
8134 return UsedBits;
8135 }
8136
8137 /// \brief Get the size of the slice to be loaded in bytes.
8138 unsigned getLoadedSize() const {
8139 unsigned SliceSize = getUsedBits().countPopulation();
8140 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8141 return SliceSize / 8;
8142 }
8143
8144 /// \brief Get the type that will be loaded for this slice.
8145 /// Note: This may not be the final type for the slice.
8146 EVT getLoadedType() const {
8147 assert(DAG && "Missing context");
8148 LLVMContext &Ctxt = *DAG->getContext();
8149 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8150 }
8151
8152 /// \brief Get the alignment of the load used for this slice.
8153 unsigned getAlignment() const {
8154 unsigned Alignment = Origin->getAlignment();
8155 unsigned Offset = getOffsetFromBase();
8156 if (Offset != 0)
8157 Alignment = MinAlign(Alignment, Alignment + Offset);
8158 return Alignment;
8159 }
8160
8161 /// \brief Check if this slice can be rewritten with legal operations.
8162 bool isLegal() const {
8163 // An invalid slice is not legal.
8164 if (!Origin || !Inst || !DAG)
8165 return false;
8166
8167 // Offsets are for indexed load only, we do not handle that.
8168 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8169 return false;
8170
8171 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8172
8173 // Check that the type is legal.
8174 EVT SliceType = getLoadedType();
8175 if (!TLI.isTypeLegal(SliceType))
8176 return false;
8177
8178 // Check that the load is legal for this type.
8179 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8180 return false;
8181
8182 // Check that the offset can be computed.
8183 // 1. Check its type.
8184 EVT PtrType = Origin->getBasePtr().getValueType();
8185 if (PtrType == MVT::Untyped || PtrType.isExtended())
8186 return false;
8187
8188 // 2. Check that it fits in the immediate.
8189 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8190 return false;
8191
8192 // 3. Check that the computation is legal.
8193 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8194 return false;
8195
8196 // Check that the zext is legal if it needs one.
8197 EVT TruncateType = Inst->getValueType(0);
8198 if (TruncateType != SliceType &&
8199 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8200 return false;
8201
8202 return true;
8203 }
8204
8205 /// \brief Get the offset in bytes of this slice in the original chunk of
8206 /// bits.
Stephen Hinesdce4a402014-05-29 02:49:00 -07008207 /// \pre DAG != nullptr.
Quentin Colombet83f743a2013-10-11 18:29:42 +00008208 uint64_t getOffsetFromBase() const {
8209 assert(DAG && "Missing context.");
8210 bool IsBigEndian =
8211 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8212 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8213 uint64_t Offset = Shift / 8;
8214 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8215 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8216 "The size of the original loaded type is not a multiple of a"
8217 " byte.");
8218 // If Offset is bigger than TySizeInBytes, it means we are loading all
8219 // zeros. This should have been optimized before in the process.
8220 assert(TySizeInBytes > Offset &&
8221 "Invalid shift amount for given loaded size");
8222 if (IsBigEndian)
8223 Offset = TySizeInBytes - Offset - getLoadedSize();
8224 return Offset;
8225 }
8226
8227 /// \brief Generate the sequence of instructions to load the slice
8228 /// represented by this object and redirect the uses of this slice to
8229 /// this new sequence of instructions.
8230 /// \pre this->Inst && this->Origin are valid Instructions and this
8231 /// object passed the legal check: LoadedSlice::isLegal returned true.
8232 /// \return The last instruction of the sequence used to load the slice.
8233 SDValue loadSlice() const {
8234 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8235 const SDValue &OldBaseAddr = Origin->getBasePtr();
8236 SDValue BaseAddr = OldBaseAddr;
8237 // Get the offset in that chunk of bytes w.r.t. the endianess.
8238 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8239 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8240 if (Offset) {
8241 // BaseAddr = BaseAddr + Offset.
8242 EVT ArithType = BaseAddr.getValueType();
8243 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8244 DAG->getConstant(Offset, ArithType));
8245 }
8246
8247 // Create the type of the loaded slice according to its size.
8248 EVT SliceType = getLoadedType();
8249
8250 // Create the load for the slice.
8251 SDValue LastInst = DAG->getLoad(
8252 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8253 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8254 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8255 // If the final type is not the same as the loaded type, this means that
8256 // we have to pad with zero. Create a zero extend for that.
8257 EVT FinalType = Inst->getValueType(0);
8258 if (SliceType != FinalType)
8259 LastInst =
8260 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8261 return LastInst;
8262 }
8263
8264 /// \brief Check if this slice can be merged with an expensive cross register
8265 /// bank copy. E.g.,
8266 /// i = load i32
8267 /// f = bitcast i32 i to float
8268 bool canMergeExpensiveCrossRegisterBankCopy() const {
8269 if (!Inst || !Inst->hasOneUse())
8270 return false;
8271 SDNode *Use = *Inst->use_begin();
8272 if (Use->getOpcode() != ISD::BITCAST)
8273 return false;
8274 assert(DAG && "Missing context");
8275 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8276 EVT ResVT = Use->getValueType(0);
8277 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8278 const TargetRegisterClass *ArgRC =
8279 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8280 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8281 return false;
8282
8283 // At this point, we know that we perform a cross-register-bank copy.
8284 // Check if it is expensive.
8285 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8286 // Assume bitcasts are cheap, unless both register classes do not
8287 // explicitly share a common sub class.
8288 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8289 return false;
8290
8291 // Check if it will be merged with the load.
8292 // 1. Check the alignment constraint.
8293 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8294 ResVT.getTypeForEVT(*DAG->getContext()));
8295
8296 if (RequiredAlignment > getAlignment())
8297 return false;
8298
8299 // 2. Check that the load is a legal operation for that type.
8300 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8301 return false;
8302
8303 // 3. Check that we do not have a zext in the way.
8304 if (Inst->getValueType(0) != getLoadedType())
8305 return false;
8306
8307 return true;
8308 }
8309};
8310}
8311
Quentin Colombet83f743a2013-10-11 18:29:42 +00008312/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8313/// \p UsedBits looks like 0..0 1..1 0..0.
8314static bool areUsedBitsDense(const APInt &UsedBits) {
8315 // If all the bits are one, this is dense!
8316 if (UsedBits.isAllOnesValue())
8317 return true;
8318
8319 // Get rid of the unused bits on the right.
8320 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8321 // Get rid of the unused bits on the left.
8322 if (NarrowedUsedBits.countLeadingZeros())
8323 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8324 // Check that the chunk of bits is completely used.
8325 return NarrowedUsedBits.isAllOnesValue();
8326}
8327
8328/// \brief Check whether or not \p First and \p Second are next to each other
8329/// in memory. This means that there is no hole between the bits loaded
8330/// by \p First and the bits loaded by \p Second.
8331static bool areSlicesNextToEachOther(const LoadedSlice &First,
8332 const LoadedSlice &Second) {
8333 assert(First.Origin == Second.Origin && First.Origin &&
8334 "Unable to match different memory origins.");
8335 APInt UsedBits = First.getUsedBits();
8336 assert((UsedBits & Second.getUsedBits()) == 0 &&
8337 "Slices are not supposed to overlap.");
8338 UsedBits |= Second.getUsedBits();
8339 return areUsedBitsDense(UsedBits);
8340}
8341
8342/// \brief Adjust the \p GlobalLSCost according to the target
8343/// paring capabilities and the layout of the slices.
8344/// \pre \p GlobalLSCost should account for at least as many loads as
8345/// there is in the slices in \p LoadedSlices.
8346static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8347 LoadedSlice::Cost &GlobalLSCost) {
8348 unsigned NumberOfSlices = LoadedSlices.size();
8349 // If there is less than 2 elements, no pairing is possible.
8350 if (NumberOfSlices < 2)
8351 return;
8352
8353 // Sort the slices so that elements that are likely to be next to each
8354 // other in memory are next to each other in the list.
Stephen Hines36b56882014-04-23 16:57:46 -07008355 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8356 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8357 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8358 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8359 });
Quentin Colombet83f743a2013-10-11 18:29:42 +00008360 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8361 // First (resp. Second) is the first (resp. Second) potentially candidate
8362 // to be placed in a paired load.
Stephen Hinesdce4a402014-05-29 02:49:00 -07008363 const LoadedSlice *First = nullptr;
8364 const LoadedSlice *Second = nullptr;
Quentin Colombet83f743a2013-10-11 18:29:42 +00008365 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8366 // Set the beginning of the pair.
8367 First = Second) {
8368
8369 Second = &LoadedSlices[CurrSlice];
8370
8371 // If First is NULL, it means we start a new pair.
8372 // Get to the next slice.
8373 if (!First)
8374 continue;
8375
8376 EVT LoadedType = First->getLoadedType();
8377
8378 // If the types of the slices are different, we cannot pair them.
8379 if (LoadedType != Second->getLoadedType())
8380 continue;
8381
8382 // Check if the target supplies paired loads for this type.
8383 unsigned RequiredAlignment = 0;
8384 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8385 // move to the next pair, this type is hopeless.
Stephen Hinesdce4a402014-05-29 02:49:00 -07008386 Second = nullptr;
Quentin Colombet83f743a2013-10-11 18:29:42 +00008387 continue;
8388 }
8389 // Check if we meet the alignment requirement.
8390 if (RequiredAlignment > First->getAlignment())
8391 continue;
8392
8393 // Check that both loads are next to each other in memory.
8394 if (!areSlicesNextToEachOther(*First, *Second))
8395 continue;
8396
8397 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8398 --GlobalLSCost.Loads;
8399 // Move to the next pair.
Stephen Hinesdce4a402014-05-29 02:49:00 -07008400 Second = nullptr;
Quentin Colombet83f743a2013-10-11 18:29:42 +00008401 }
8402}
8403
8404/// \brief Check the profitability of all involved LoadedSlice.
8405/// Currently, it is considered profitable if there is exactly two
8406/// involved slices (1) which are (2) next to each other in memory, and
8407/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8408///
8409/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8410/// the elements themselves.
8411///
8412/// FIXME: When the cost model will be mature enough, we can relax
8413/// constraints (1) and (2).
8414static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8415 const APInt &UsedBits, bool ForCodeSize) {
8416 unsigned NumberOfSlices = LoadedSlices.size();
8417 if (StressLoadSlicing)
8418 return NumberOfSlices > 1;
8419
8420 // Check (1).
8421 if (NumberOfSlices != 2)
8422 return false;
8423
8424 // Check (2).
8425 if (!areUsedBitsDense(UsedBits))
8426 return false;
8427
8428 // Check (3).
8429 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8430 // The original code has one big load.
8431 OrigCost.Loads = 1;
8432 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8433 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8434 // Accumulate the cost of all the slices.
8435 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8436 GlobalSlicingCost += SliceCost;
8437
8438 // Account as cost in the original configuration the gain obtained
8439 // with the current slices.
8440 OrigCost.addSliceGain(LS);
8441 }
8442
8443 // If the target supports paired load, adjust the cost accordingly.
8444 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8445 return OrigCost > GlobalSlicingCost;
8446}
8447
8448/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8449/// operations, split it in the various pieces being extracted.
8450///
8451/// This sort of thing is introduced by SROA.
8452/// This slicing takes care not to insert overlapping loads.
8453/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8454bool DAGCombiner::SliceUpLoad(SDNode *N) {
8455 if (Level < AfterLegalizeDAG)
8456 return false;
8457
8458 LoadSDNode *LD = cast<LoadSDNode>(N);
8459 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8460 !LD->getValueType(0).isInteger())
8461 return false;
8462
8463 // Keep track of already used bits to detect overlapping values.
8464 // In that case, we will just abort the transformation.
8465 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8466
8467 SmallVector<LoadedSlice, 4> LoadedSlices;
8468
8469 // Check if this load is used as several smaller chunks of bits.
8470 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8471 // of computation for each trunc.
8472 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8473 UI != UIEnd; ++UI) {
8474 // Skip the uses of the chain.
8475 if (UI.getUse().getResNo() != 0)
8476 continue;
8477
8478 SDNode *User = *UI;
8479 unsigned Shift = 0;
8480
8481 // Check if this is a trunc(lshr).
8482 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8483 isa<ConstantSDNode>(User->getOperand(1))) {
8484 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8485 User = *User->use_begin();
8486 }
8487
8488 // At this point, User is a Truncate, iff we encountered, trunc or
8489 // trunc(lshr).
8490 if (User->getOpcode() != ISD::TRUNCATE)
8491 return false;
8492
8493 // The width of the type must be a power of 2 and greater than 8-bits.
8494 // Otherwise the load cannot be represented in LLVM IR.
Stephen Hines36b56882014-04-23 16:57:46 -07008495 // Moreover, if we shifted with a non-8-bits multiple, the slice
8496 // will be across several bytes. We do not support that.
Quentin Colombet83f743a2013-10-11 18:29:42 +00008497 unsigned Width = User->getValueSizeInBits(0);
8498 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8499 return 0;
8500
8501 // Build the slice for this chain of computations.
8502 LoadedSlice LS(User, LD, Shift, &DAG);
8503 APInt CurrentUsedBits = LS.getUsedBits();
8504
8505 // Check if this slice overlaps with another.
8506 if ((CurrentUsedBits & UsedBits) != 0)
8507 return false;
8508 // Update the bits used globally.
8509 UsedBits |= CurrentUsedBits;
8510
8511 // Check if the new slice would be legal.
8512 if (!LS.isLegal())
8513 return false;
8514
8515 // Record the slice.
8516 LoadedSlices.push_back(LS);
8517 }
8518
8519 // Abort slicing if it does not seem to be profitable.
8520 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8521 return false;
8522
8523 ++SlicedLoads;
8524
8525 // Rewrite each chain to use an independent load.
8526 // By construction, each chain can be represented by a unique load.
8527
8528 // Prepare the argument for the new token factor for all the slices.
8529 SmallVector<SDValue, 8> ArgChains;
8530 for (SmallVectorImpl<LoadedSlice>::const_iterator
8531 LSIt = LoadedSlices.begin(),
8532 LSItEnd = LoadedSlices.end();
8533 LSIt != LSItEnd; ++LSIt) {
8534 SDValue SliceInst = LSIt->loadSlice();
8535 CombineTo(LSIt->Inst, SliceInst, true);
8536 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8537 SliceInst = SliceInst.getOperand(0);
8538 assert(SliceInst->getOpcode() == ISD::LOAD &&
8539 "It takes more than a zext to get to the loaded slice!!");
8540 ArgChains.push_back(SliceInst.getValue(1));
8541 }
8542
8543 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Stephen Hinesdce4a402014-05-29 02:49:00 -07008544 ArgChains);
Quentin Colombet83f743a2013-10-11 18:29:42 +00008545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8546 return true;
8547}
8548
Chris Lattner2392ae72010-04-15 04:48:01 +00008549/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8550/// load is having specific bytes cleared out. If so, return the byte size
8551/// being masked out and the shift amount.
8552static std::pair<unsigned, unsigned>
8553CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8554 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008555
Chris Lattner2392ae72010-04-15 04:48:01 +00008556 // Check for the structure we're looking for.
8557 if (V->getOpcode() != ISD::AND ||
8558 !isa<ConstantSDNode>(V->getOperand(1)) ||
8559 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8560 return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008561
Chris Lattnere6987582010-04-15 06:10:49 +00008562 // Check the chain and pointer.
Chris Lattner2392ae72010-04-15 04:48:01 +00008563 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattnere6987582010-04-15 06:10:49 +00008564 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008565
Chris Lattnere6987582010-04-15 06:10:49 +00008566 // The store should be chained directly to the load or be an operand of a
8567 // tokenfactor.
8568 if (LD == Chain.getNode())
8569 ; // ok.
8570 else if (Chain->getOpcode() != ISD::TokenFactor)
8571 return Result; // Fail.
8572 else {
8573 bool isOk = false;
8574 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8575 if (Chain->getOperand(i).getNode() == LD) {
8576 isOk = true;
8577 break;
8578 }
8579 if (!isOk) return Result;
8580 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008581
Chris Lattner2392ae72010-04-15 04:48:01 +00008582 // This only handles simple types.
8583 if (V.getValueType() != MVT::i16 &&
8584 V.getValueType() != MVT::i32 &&
8585 V.getValueType() != MVT::i64)
8586 return Result;
8587
8588 // Check the constant mask. Invert it so that the bits being masked out are
8589 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8590 // follow the sign bit for uniformity.
8591 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008592 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008593 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerc6af2432013-05-24 22:23:49 +00008594 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner2392ae72010-04-15 04:48:01 +00008595 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8596 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008597
Chris Lattner2392ae72010-04-15 04:48:01 +00008598 // See if we have a continuous run of bits. If so, we have 0*1+0*
8599 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8600 return Result;
8601
8602 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8603 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8604 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008605
Chris Lattner2392ae72010-04-15 04:48:01 +00008606 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8607 switch (MaskedBytes) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008608 case 1:
8609 case 2:
Chris Lattner2392ae72010-04-15 04:48:01 +00008610 case 4: break;
8611 default: return Result; // All one mask, or 5-byte mask.
8612 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008613
Chris Lattner2392ae72010-04-15 04:48:01 +00008614 // Verify that the first bit starts at a multiple of mask so that the access
8615 // is aligned the same as the access width.
8616 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008617
Chris Lattner2392ae72010-04-15 04:48:01 +00008618 Result.first = MaskedBytes;
8619 Result.second = NotMaskTZ/8;
8620 return Result;
8621}
8622
8623
8624/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8625/// provides a value as specified by MaskInfo. If so, replace the specified
8626/// store with a narrower store of truncated IVal.
8627static SDNode *
8628ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8629 SDValue IVal, StoreSDNode *St,
8630 DAGCombiner *DC) {
8631 unsigned NumBytes = MaskInfo.first;
8632 unsigned ByteShift = MaskInfo.second;
8633 SelectionDAG &DAG = DC->getDAG();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008634
Chris Lattner2392ae72010-04-15 04:48:01 +00008635 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8636 // that uses this. If not, this is not a replacement.
8637 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8638 ByteShift*8, (ByteShift+NumBytes)*8);
Stephen Hinesdce4a402014-05-29 02:49:00 -07008639 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008640
Chris Lattner2392ae72010-04-15 04:48:01 +00008641 // Check that it is legal on the target to do this. It is legal if the new
8642 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8643 // legalization.
8644 MVT VT = MVT::getIntegerVT(NumBytes*8);
8645 if (!DC->isTypeLegal(VT))
Stephen Hinesdce4a402014-05-29 02:49:00 -07008646 return nullptr;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008647
Chris Lattner2392ae72010-04-15 04:48:01 +00008648 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8649 // shifted by ByteShift and truncated down to NumBytes.
8650 if (ByteShift)
Andrew Trickac6d9be2013-05-25 02:42:55 +00008651 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Anderson95771af2011-02-25 21:41:48 +00008652 DAG.getConstant(ByteShift*8,
8653 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner2392ae72010-04-15 04:48:01 +00008654
8655 // Figure out the offset for the store and the alignment of the access.
8656 unsigned StOffset;
8657 unsigned NewAlign = St->getAlignment();
8658
8659 if (DAG.getTargetLoweringInfo().isLittleEndian())
8660 StOffset = ByteShift;
8661 else
8662 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008663
Chris Lattner2392ae72010-04-15 04:48:01 +00008664 SDValue Ptr = St->getBasePtr();
8665 if (StOffset) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00008666 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner2392ae72010-04-15 04:48:01 +00008667 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8668 NewAlign = MinAlign(NewAlign, StOffset);
8669 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008670
Chris Lattner2392ae72010-04-15 04:48:01 +00008671 // Truncate down to the new size.
Andrew Trickac6d9be2013-05-25 02:42:55 +00008672 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008673
Chris Lattner2392ae72010-04-15 04:48:01 +00008674 ++OpsNarrowed;
Andrew Trickac6d9be2013-05-25 02:42:55 +00008675 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner6229d0a2010-09-21 18:41:36 +00008676 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner2392ae72010-04-15 04:48:01 +00008677 false, false, NewAlign).getNode();
8678}
8679
Evan Cheng8b944d32009-05-28 00:35:15 +00008680
8681/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8682/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8683/// of the loaded bits, try narrowing the load and store if it would end up
8684/// being a win for performance or code size.
8685SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8686 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Chengcdcecc02009-05-28 18:41:02 +00008687 if (ST->isVolatile())
8688 return SDValue();
8689
Evan Cheng8b944d32009-05-28 00:35:15 +00008690 SDValue Chain = ST->getChain();
8691 SDValue Value = ST->getValue();
8692 SDValue Ptr = ST->getBasePtr();
Owen Andersone50ed302009-08-10 22:56:29 +00008693 EVT VT = Value.getValueType();
Evan Cheng8b944d32009-05-28 00:35:15 +00008694
8695 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Chengcdcecc02009-05-28 18:41:02 +00008696 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008697
8698 unsigned Opc = Value.getOpcode();
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008699
Chris Lattner2392ae72010-04-15 04:48:01 +00008700 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8701 // is a byte mask indicating a consecutive number of bytes, check to see if
8702 // Y is known to provide just those bytes. If so, we try to replace the
8703 // load + replace + store sequence with a single (narrower) store, which makes
8704 // the load dead.
8705 if (Opc == ISD::OR) {
8706 std::pair<unsigned, unsigned> MaskedLoad;
8707 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8708 if (MaskedLoad.first)
8709 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8710 Value.getOperand(1), ST,this))
8711 return SDValue(NewST, 0);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008712
Chris Lattner2392ae72010-04-15 04:48:01 +00008713 // Or is commutative, so try swapping X and Y.
8714 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8715 if (MaskedLoad.first)
8716 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8717 Value.getOperand(0), ST,this))
8718 return SDValue(NewST, 0);
8719 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00008720
Evan Cheng8b944d32009-05-28 00:35:15 +00008721 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8722 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Chengcdcecc02009-05-28 18:41:02 +00008723 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008724
8725 SDValue N0 = Value.getOperand(0);
Dan Gohman24bde5b2010-09-02 21:18:42 +00008726 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8727 Chain == SDValue(N0.getNode(), 1)) {
Evan Cheng8b944d32009-05-28 00:35:15 +00008728 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerfa459012010-09-21 16:08:50 +00008729 if (LD->getBasePtr() != Ptr ||
8730 LD->getPointerInfo().getAddrSpace() !=
8731 ST->getPointerInfo().getAddrSpace())
Evan Chengcdcecc02009-05-28 18:41:02 +00008732 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008733
8734 // Find the type to narrow it the load / op / store to.
8735 SDValue N1 = Value.getOperand(1);
8736 unsigned BitWidth = N1.getValueSizeInBits();
8737 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8738 if (Opc == ISD::AND)
8739 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Chengd3c76bb2009-05-28 23:52:18 +00008740 if (Imm == 0 || Imm.isAllOnesValue())
8741 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008742 unsigned ShAmt = Imm.countTrailingZeros();
8743 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8744 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson23b9b192009-08-12 00:36:31 +00008745 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008746 while (NewBW < BitWidth &&
Evan Chengcdcecc02009-05-28 18:41:02 +00008747 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Cheng8b944d32009-05-28 00:35:15 +00008748 TLI.isNarrowingProfitable(VT, NewVT))) {
8749 NewBW = NextPowerOf2(NewBW);
Owen Anderson23b9b192009-08-12 00:36:31 +00008750 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Cheng8b944d32009-05-28 00:35:15 +00008751 }
Evan Chengcdcecc02009-05-28 18:41:02 +00008752 if (NewBW >= BitWidth)
8753 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008754
8755 // If the lsb changed does not start at the type bitwidth boundary,
8756 // start at the previous one.
8757 if (ShAmt % NewBW)
8758 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren981b9632012-12-12 01:13:50 +00008759 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8760 std::min(BitWidth, ShAmt + NewBW));
Evan Cheng8b944d32009-05-28 00:35:15 +00008761 if ((Imm & Mask) == Imm) {
8762 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8763 if (Opc == ISD::AND)
8764 NewImm ^= APInt::getAllOnesValue(NewBW);
8765 uint64_t PtrOff = ShAmt / 8;
8766 // For big endian targets, we need to adjust the offset to the pointer to
8767 // load the correct bytes.
8768 if (TLI.isBigEndian())
Evan Chengcdcecc02009-05-28 18:41:02 +00008769 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Cheng8b944d32009-05-28 00:35:15 +00008770
8771 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008772 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008773 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Chengcdcecc02009-05-28 18:41:02 +00008774 return SDValue();
8775
Andrew Trickac6d9be2013-05-25 02:42:55 +00008776 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Cheng8b944d32009-05-28 00:35:15 +00008777 Ptr.getValueType(), Ptr,
8778 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008779 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Cheng8b944d32009-05-28 00:35:15 +00008780 LD->getChain(), NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008781 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008782 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00008783 LD->isInvariant(), NewAlign,
8784 LD->getTBAAInfo());
Andrew Trickac6d9be2013-05-25 02:42:55 +00008785 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Cheng8b944d32009-05-28 00:35:15 +00008786 DAG.getConstant(NewImm, NewVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00008787 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Cheng8b944d32009-05-28 00:35:15 +00008788 NewVal, NewPtr,
Chris Lattnerfa459012010-09-21 16:08:50 +00008789 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene1e559442010-02-15 17:00:31 +00008790 false, false, NewAlign);
Evan Cheng8b944d32009-05-28 00:35:15 +00008791
8792 AddToWorkList(NewPtr.getNode());
8793 AddToWorkList(NewLD.getNode());
8794 AddToWorkList(NewVal.getNode());
8795 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008796 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Cheng8b944d32009-05-28 00:35:15 +00008797 ++OpsNarrowed;
8798 return NewST;
8799 }
8800 }
8801
Evan Chengcdcecc02009-05-28 18:41:02 +00008802 return SDValue();
Evan Cheng8b944d32009-05-28 00:35:15 +00008803}
8804
Evan Cheng31959b12011-02-02 01:06:55 +00008805/// TransformFPLoadStorePair - For a given floating point load / store pair,
8806/// if the load value isn't used by any other operations, then consider
8807/// transforming the pair to integer load / store operations if the target
8808/// deems the transformation profitable.
8809SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8810 StoreSDNode *ST = cast<StoreSDNode>(N);
8811 SDValue Chain = ST->getChain();
8812 SDValue Value = ST->getValue();
8813 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8814 Value.hasOneUse() &&
8815 Chain == SDValue(Value.getNode(), 1)) {
8816 LoadSDNode *LD = cast<LoadSDNode>(Value);
8817 EVT VT = LD->getMemoryVT();
8818 if (!VT.isFloatingPoint() ||
8819 VT != ST->getMemoryVT() ||
8820 LD->isNonTemporal() ||
8821 ST->isNonTemporal() ||
8822 LD->getPointerInfo().getAddrSpace() != 0 ||
8823 ST->getPointerInfo().getAddrSpace() != 0)
8824 return SDValue();
8825
8826 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8827 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8828 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8829 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8830 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8831 return SDValue();
8832
8833 unsigned LDAlign = LD->getAlignment();
8834 unsigned STAlign = ST->getAlignment();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00008835 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmow3574eca2012-10-08 16:38:25 +00008836 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Cheng31959b12011-02-02 01:06:55 +00008837 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8838 return SDValue();
8839
Andrew Trickac6d9be2013-05-25 02:42:55 +00008840 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Cheng31959b12011-02-02 01:06:55 +00008841 LD->getChain(), LD->getBasePtr(),
8842 LD->getPointerInfo(),
Pete Cooperd752e0f2011-11-08 18:42:53 +00008843 false, false, false, LDAlign);
Evan Cheng31959b12011-02-02 01:06:55 +00008844
Andrew Trickac6d9be2013-05-25 02:42:55 +00008845 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Cheng31959b12011-02-02 01:06:55 +00008846 NewLD, ST->getBasePtr(),
8847 ST->getPointerInfo(),
8848 false, false, STAlign);
8849
8850 AddToWorkList(NewLD.getNode());
8851 AddToWorkList(NewST.getNode());
8852 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00008853 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Cheng31959b12011-02-02 01:06:55 +00008854 ++LdStFP2Int;
8855 return NewST;
8856 }
8857
8858 return SDValue();
8859}
8860
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008861/// Helper struct to parse and store a memory address as base + index + offset.
8862/// We ignore sign extensions when it is safe to do so.
8863/// The following two expressions are not equivalent. To differentiate we need
8864/// to store whether there was a sign extension involved in the index
8865/// computation.
8866/// (load (i64 add (i64 copyfromreg %c)
8867/// (i64 signextend (add (i8 load %index)
8868/// (i8 1))))
8869/// vs
8870///
8871/// (load (i64 add (i64 copyfromreg %c)
8872/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8873/// (i32 1)))))
8874struct BaseIndexOffset {
8875 SDValue Base;
8876 SDValue Index;
8877 int64_t Offset;
8878 bool IsIndexSignExt;
8879
8880 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8881
8882 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8883 bool IsIndexSignExt) :
8884 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8885
8886 bool equalBaseIndex(const BaseIndexOffset &Other) {
8887 return Other.Base == Base && Other.Index == Index &&
8888 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotemc653de62012-10-03 16:11:15 +00008889 }
8890
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008891 /// Parses tree in Ptr for base, index, offset addresses.
8892 static BaseIndexOffset match(SDValue Ptr) {
8893 bool IsIndexSignExt = false;
8894
Juergen Ributzka915e9362013-08-21 21:53:38 +00008895 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8896 // instruction, then it could be just the BASE or everything else we don't
8897 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008898 if (Ptr->getOpcode() != ISD::ADD)
8899 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8900
Juergen Ributzka915e9362013-08-21 21:53:38 +00008901 // We know that we have at least an ADD instruction. Try to pattern match
8902 // the simple case of BASE + OFFSET.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008903 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8904 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8905 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8906 IsIndexSignExt);
8907 }
8908
Juergen Ributzka915e9362013-08-21 21:53:38 +00008909 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008910 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka915e9362013-08-21 21:53:38 +00008911 // (i64 add (i64 %array_ptr)
8912 // (i64 mul (i64 %induction_var)
8913 // (i64 %element_size)))
Juergen Ributzka2b884bc2013-08-28 22:33:58 +00008914 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka915e9362013-08-21 21:53:38 +00008915 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka915e9362013-08-21 21:53:38 +00008916
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008917 // Look at Base + Index + Offset cases.
8918 SDValue Base = Ptr->getOperand(0);
8919 SDValue IndexOffset = Ptr->getOperand(1);
8920
8921 // Skip signextends.
8922 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8923 IndexOffset = IndexOffset->getOperand(0);
8924 IsIndexSignExt = true;
8925 }
8926
8927 // Either the case of Base + Index (no offset) or something else.
8928 if (IndexOffset->getOpcode() != ISD::ADD)
8929 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8930
8931 // Now we have the case of Base + Index + offset.
8932 SDValue Index = IndexOffset->getOperand(0);
8933 SDValue Offset = IndexOffset->getOperand(1);
8934
8935 if (!isa<ConstantSDNode>(Offset))
8936 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8937
8938 // Ignore signextends.
8939 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8940 Index = Index->getOperand(0);
8941 IsIndexSignExt = true;
8942 } else IsIndexSignExt = false;
8943
8944 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8945 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8946 }
8947};
Nadav Rotemc653de62012-10-03 16:11:15 +00008948
8949/// Holds a pointer to an LSBaseSDNode as well as information on where it
8950/// is located in a sequence of memory operations connected by a chain.
8951struct MemOpLink {
8952 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8953 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8954 // Ptr to the mem node.
8955 LSBaseSDNode *MemNode;
8956 // Offset from the base ptr.
8957 int64_t OffsetFromBase;
8958 // What is the sequence number of this mem node.
8959 // Lowest mem operand in the DAG starts at zero.
8960 unsigned SequenceNum;
8961};
8962
Nadav Rotemc653de62012-10-03 16:11:15 +00008963bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8964 EVT MemVT = St->getMemoryVT();
8965 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00008966 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8967 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotemc653de62012-10-03 16:11:15 +00008968
8969 // Don't merge vectors into wider inputs.
8970 if (MemVT.isVector() || !MemVT.isSimple())
8971 return false;
8972
8973 // Perform an early exit check. Do not bother looking at stored values that
8974 // are not constants or loads.
8975 SDValue StoredVal = St->getValue();
8976 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8977 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8978 !IsLoadSrc)
8979 return false;
8980
8981 // Only look at ends of store sequences.
8982 SDValue Chain = SDValue(St, 1);
8983 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8984 return false;
8985
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008986 // This holds the base pointer, index, and the offset in bytes from the base
8987 // pointer.
8988 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00008989
8990 // We must have a base and an offset.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008991 if (!BasePtr.Base.getNode())
Nadav Rotemc653de62012-10-03 16:11:15 +00008992 return false;
8993
8994 // Do not handle stores to undef base pointers.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00008995 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotemc653de62012-10-03 16:11:15 +00008996 return false;
8997
Nadav Rotem90e11dc2012-11-29 00:00:08 +00008998 // Save the LoadSDNodes that we find in the chain.
8999 // We need to make sure that these nodes do not interfere with
9000 // any of the store nodes.
9001 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9002
9003 // Save the StoreSDNodes that we find in the chain.
Nadav Rotemc653de62012-10-03 16:11:15 +00009004 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009005
Nadav Rotemc653de62012-10-03 16:11:15 +00009006 // Walk up the chain and look for nodes with offsets from the same
9007 // base pointer. Stop when reaching an instruction with a different kind
9008 // or instruction which has a different base pointer.
9009 unsigned Seq = 0;
9010 StoreSDNode *Index = St;
9011 while (Index) {
9012 // If the chain has more than one use, then we can't reorder the mem ops.
9013 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9014 break;
9015
9016 // Find the base pointer and offset for this memory node.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009017 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00009018
9019 // Check that the base pointer is the same as the original one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009020 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00009021 break;
9022
9023 // Check that the alignment is the same.
9024 if (Index->getAlignment() != St->getAlignment())
9025 break;
9026
9027 // The memory operands must not be volatile.
9028 if (Index->isVolatile() || Index->isIndexed())
9029 break;
9030
9031 // No truncation.
9032 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9033 if (St->isTruncatingStore())
9034 break;
9035
9036 // The stored memory type must be the same.
9037 if (Index->getMemoryVT() != MemVT)
9038 break;
9039
9040 // We do not allow unaligned stores because we want to prevent overriding
9041 // stores.
9042 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9043 break;
9044
9045 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009046 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotemc653de62012-10-03 16:11:15 +00009047
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009048 // Find the next memory operand in the chain. If the next operand in the
9049 // chain is a store then move up and continue the scan with the next
9050 // memory operand. If the next operand is a load save it and use alias
9051 // information to check if it interferes with anything.
9052 SDNode *NextInChain = Index->getChain().getNode();
9053 while (1) {
Nadav Rotemdde785c2012-12-06 17:34:13 +00009054 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009055 // We found a store node. Use it for the next iteration.
Nadav Rotemdde785c2012-12-06 17:34:13 +00009056 Index = STn;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009057 break;
9058 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling13498992013-11-25 18:08:07 +00009059 if (Ldn->isVolatile()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07009060 Index = nullptr;
Bill Wendling13498992013-11-25 18:08:07 +00009061 break;
9062 }
9063
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009064 // Save the load node for later. Continue the scan.
9065 AliasLoadNodes.push_back(Ldn);
9066 NextInChain = Ldn->getChain().getNode();
9067 continue;
9068 } else {
Stephen Hinesdce4a402014-05-29 02:49:00 -07009069 Index = nullptr;
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009070 break;
9071 }
9072 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009073 }
9074
9075 // Check if there is anything to merge.
9076 if (StoreNodes.size() < 2)
9077 return false;
9078
9079 // Sort the memory operands according to their distance from the base pointer.
9080 std::sort(StoreNodes.begin(), StoreNodes.end(),
Stephen Hines36b56882014-04-23 16:57:46 -07009081 [](MemOpLink LHS, MemOpLink RHS) {
9082 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9083 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9084 LHS.SequenceNum > RHS.SequenceNum);
9085 });
Nadav Rotemc653de62012-10-03 16:11:15 +00009086
9087 // Scan the memory operations on the chain and find the first non-consecutive
9088 // store memory address.
9089 unsigned LastConsecutiveStore = 0;
9090 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemdde785c2012-12-06 17:34:13 +00009091 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9092
9093 // Check that the addresses are consecutive starting from the second
9094 // element in the list of stores.
9095 if (i > 0) {
9096 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9097 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9098 break;
9099 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009100
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009101 bool Alias = false;
9102 // Check if this store interferes with any of the loads that we found.
9103 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9104 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9105 Alias = true;
9106 break;
9107 }
Nadav Rotem90e11dc2012-11-29 00:00:08 +00009108 // We found a load that alias with this store. Stop the sequence.
9109 if (Alias)
9110 break;
9111
Nadav Rotemc653de62012-10-03 16:11:15 +00009112 // Mark this node as useful.
9113 LastConsecutiveStore = i;
9114 }
9115
9116 // The node with the lowest store address.
9117 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9118
9119 // Store the constants into memory as one consecutive store.
9120 if (!IsLoadSrc) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009121 unsigned LastLegalType = 0;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009122 unsigned LastLegalVectorType = 0;
9123 bool NonZero = false;
Nadav Rotemc653de62012-10-03 16:11:15 +00009124 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9125 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9126 SDValue StoredVal = St->getValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009127
9128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00009129 NonZero |= !C->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009130 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramerebd7eab2012-10-05 18:19:44 +00009131 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009132 } else {
Stephen Hines36b56882014-04-23 16:57:46 -07009133 // Non-constant.
Nadav Rotemc653de62012-10-03 16:11:15 +00009134 break;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009135 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009136
Nadav Rotemc653de62012-10-03 16:11:15 +00009137 // Find a legal type for the constant store.
9138 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9139 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9140 if (TLI.isTypeLegal(StoreTy))
9141 LastLegalType = i+1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00009142 // Or check whether a truncstore is legal.
9143 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9144 TargetLowering::TypePromoteInteger) {
9145 EVT LegalizedStoredValueTy =
9146 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9147 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9148 LastLegalType = i+1;
9149 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009150
9151 // Find a legal type for the vector store.
9152 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9153 if (TLI.isTypeLegal(Ty))
9154 LastLegalVectorType = i + 1;
Nadav Rotemc653de62012-10-03 16:11:15 +00009155 }
9156
Bob Wilson99d8e762012-12-20 01:36:20 +00009157 // We only use vectors if the constant is known to be zero and the
9158 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009159 if (NonZero || NoVectors)
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009160 LastLegalVectorType = 0;
9161
Nadav Rotemc653de62012-10-03 16:11:15 +00009162 // Check if we found a legal integer type to store.
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009163 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotemc653de62012-10-03 16:11:15 +00009164 return false;
9165
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009166 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009167 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9168
9169 // Make sure we have something to merge.
9170 if (NumElem < 2)
9171 return false;
Nadav Rotemc653de62012-10-03 16:11:15 +00009172
9173 unsigned EarliestNodeUsed = 0;
9174 for (unsigned i=0; i < NumElem; ++i) {
9175 // Find a chain for the new wide-store operand. Notice that some
9176 // of the store nodes that we found may not be selected for inclusion
9177 // in the wide store. The chain we use needs to be the chain of the
9178 // earliest store node which is *used* and replaced by the wide store.
9179 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9180 EarliestNodeUsed = i;
9181 }
9182
9183 // The earliest Node in the DAG.
9184 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009185 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00009186
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009187 SDValue StoredVal;
9188 if (UseVector) {
9189 // Find a legal type for the vector store.
9190 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9191 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9192 StoredVal = DAG.getConstant(0, Ty);
9193 } else {
9194 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9195 APInt StoreInt(StoreBW, 0);
9196
9197 // Construct a single integer constant which is made of the smaller
9198 // constant inputs.
9199 bool IsLE = TLI.isLittleEndian();
9200 for (unsigned i = 0; i < NumElem ; ++i) {
9201 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9202 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9203 SDValue Val = St->getValue();
9204 StoreInt<<=ElementSizeBytes*8;
9205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9206 StoreInt|=C->getAPIntValue().zext(StoreBW);
9207 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9208 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9209 } else {
9210 assert(false && "Invalid constant element type");
9211 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009212 }
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009213
9214 // Create the new Load and Store operations.
9215 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9216 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotemc653de62012-10-03 16:11:15 +00009217 }
9218
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009219 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotemc653de62012-10-03 16:11:15 +00009220 FirstInChain->getBasePtr(),
9221 FirstInChain->getPointerInfo(),
9222 false, false,
9223 FirstInChain->getAlignment());
9224
9225 // Replace the first store with the new store
9226 CombineTo(EarliestOp, NewStore);
9227 // Erase all other stores.
9228 for (unsigned i = 0; i < NumElem ; ++i) {
9229 if (StoreNodes[i].MemNode == EarliestOp)
9230 continue;
9231 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindola8e2b8ae2012-11-14 05:08:56 +00009232 // ReplaceAllUsesWith will replace all uses that existed when it was
9233 // called, but graph optimizations may cause new ones to appear. For
9234 // example, the case in pr14333 looks like
9235 //
9236 // St's chain -> St -> another store -> X
9237 //
9238 // And the only difference from St to the other store is the chain.
9239 // When we change it's chain to be St's chain they become identical,
9240 // get CSEed and the net result is that X is now a use of St.
9241 // Since we know that St is redundant, just iterate.
9242 while (!St->use_empty())
9243 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotemc653de62012-10-03 16:11:15 +00009244 removeFromWorkList(St);
9245 DAG.DeleteNode(St);
9246 }
9247
9248 return true;
9249 }
9250
9251 // Below we handle the case of multiple consecutive stores that
9252 // come from multiple consecutive loads. We merge them into a single
9253 // wide load and a single wide store.
9254
9255 // Look for load nodes which are used by the stored values.
9256 SmallVector<MemOpLink, 8> LoadNodes;
9257
9258 // Find acceptable loads. Loads need to have the same chain (token factor),
9259 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009260 BaseIndexOffset LdBasePtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00009261 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9262 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9263 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9264 if (!Ld) break;
9265
9266 // Loads must only have one use.
9267 if (!Ld->hasNUsesOfValue(1, 0))
9268 break;
9269
9270 // Check that the alignment is the same as the stores.
9271 if (Ld->getAlignment() != St->getAlignment())
9272 break;
9273
9274 // The memory operands must not be volatile.
9275 if (Ld->isVolatile() || Ld->isIndexed())
9276 break;
9277
9278 // We do not accept ext loads.
9279 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9280 break;
9281
9282 // The stored memory type must be the same.
9283 if (Ld->getMemoryVT() != MemVT)
9284 break;
9285
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009286 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotemc653de62012-10-03 16:11:15 +00009287 // If this is not the first ptr that we check.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009288 if (LdBasePtr.Base.getNode()) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009289 // The base ptr must be the same.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009290 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotemc653de62012-10-03 16:11:15 +00009291 break;
9292 } else {
9293 // Check that all other base pointers are the same as this one.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009294 LdBasePtr = LdPtr;
Nadav Rotemc653de62012-10-03 16:11:15 +00009295 }
9296
9297 // We found a potential memory operand to merge.
Arnold Schwaighoferf28a29b2013-04-01 18:12:58 +00009298 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotemc653de62012-10-03 16:11:15 +00009299 }
9300
9301 if (LoadNodes.size() < 2)
9302 return false;
9303
9304 // Scan the memory operations on the chain and find the first non-consecutive
9305 // load memory address. These variables hold the index in the store node
9306 // array.
9307 unsigned LastConsecutiveLoad = 0;
9308 // This variable refers to the size and not index in the array.
9309 unsigned LastLegalVectorType = 0;
9310 unsigned LastLegalIntegerType = 0;
9311 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009312 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9313 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9314 // All loads much share the same chain.
9315 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9316 break;
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009317
Nadav Rotemc653de62012-10-03 16:11:15 +00009318 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9319 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9320 break;
9321 LastConsecutiveLoad = i;
9322
9323 // Find a legal type for the vector store.
9324 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9325 if (TLI.isTypeLegal(StoreTy))
9326 LastLegalVectorType = i + 1;
9327
9328 // Find a legal type for the integer store.
9329 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9330 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9331 if (TLI.isTypeLegal(StoreTy))
9332 LastLegalIntegerType = i + 1;
Arnold Schwaighofere7370182013-04-02 15:58:51 +00009333 // Or check whether a truncstore and extload is legal.
9334 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9335 TargetLowering::TypePromoteInteger) {
9336 EVT LegalizedStoredValueTy =
9337 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9338 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9339 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9340 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9341 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9342 LastLegalIntegerType = i+1;
9343 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009344 }
9345
9346 // Only use vector types if the vector type is larger than the integer type.
9347 // If they are the same, use integers.
Nadav Rotem6cc4b8d2013-02-14 18:28:52 +00009348 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotemc653de62012-10-03 16:11:15 +00009349 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9350
9351 // We add +1 here because the LastXXX variables refer to location while
9352 // the NumElem refers to array/index size.
9353 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9354 NumElem = std::min(LastLegalType, NumElem);
9355
9356 if (NumElem < 2)
9357 return false;
9358
9359 // The earliest Node in the DAG.
9360 unsigned EarliestNodeUsed = 0;
9361 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9362 for (unsigned i=1; i<NumElem; ++i) {
9363 // Find a chain for the new wide-store operand. Notice that some
9364 // of the store nodes that we found may not be selected for inclusion
9365 // in the wide store. The chain we use needs to be the chain of the
9366 // earliest store node which is *used* and replaced by the wide store.
9367 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9368 EarliestNodeUsed = i;
9369 }
9370
9371 // Find if it is better to use vectors or integers to load and store
9372 // to memory.
9373 EVT JointMemOpVT;
9374 if (UseVectorTy) {
9375 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9376 } else {
9377 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9378 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9379 }
9380
Andrew Trickac6d9be2013-05-25 02:42:55 +00009381 SDLoc LoadDL(LoadNodes[0].MemNode);
9382 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotemc653de62012-10-03 16:11:15 +00009383
9384 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9385 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9386 FirstLoad->getChain(),
9387 FirstLoad->getBasePtr(),
9388 FirstLoad->getPointerInfo(),
9389 false, false, false,
9390 FirstLoad->getAlignment());
9391
9392 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9393 FirstInChain->getBasePtr(),
9394 FirstInChain->getPointerInfo(), false, false,
9395 FirstInChain->getAlignment());
9396
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009397 // Replace one of the loads with the new load.
9398 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9399 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9400 SDValue(NewLoad.getNode(), 1));
9401
9402 // Remove the rest of the load chains.
9403 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009404 // Replace all chain users of the old load nodes with the chain of the new
9405 // load node.
9406 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009407 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9408 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009409
Nadav Rotem2e7d3812012-10-03 19:30:31 +00009410 // Replace the first store with the new store.
9411 CombineTo(EarliestOp, NewStore);
9412 // Erase all other stores.
9413 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotemc653de62012-10-03 16:11:15 +00009414 // Remove all Store nodes.
9415 if (StoreNodes[i].MemNode == EarliestOp)
9416 continue;
9417 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9418 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9419 removeFromWorkList(St);
9420 DAG.DeleteNode(St);
9421 }
9422
9423 return true;
9424}
9425
Dan Gohman475871a2008-07-27 21:46:04 +00009426SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Cheng8b2794a2006-10-13 21:14:26 +00009427 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman475871a2008-07-27 21:46:04 +00009428 SDValue Chain = ST->getChain();
9429 SDValue Value = ST->getValue();
9430 SDValue Ptr = ST->getBasePtr();
Scott Michelfdc40a02009-02-17 22:15:04 +00009431
Evan Cheng59d5b682007-05-07 21:27:48 +00009432 // If this is a store of a bit convert, store the input value if the
Evan Cheng2c4f9432007-05-09 21:49:47 +00009433 // resultant store does not need a higher alignment than the original.
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009434 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009435 ST->isUnindexed()) {
Dan Gohman1ba519b2009-02-20 23:29:13 +00009436 unsigned OrigAlign = ST->getAlignment();
Owen Andersone50ed302009-08-10 22:56:29 +00009437 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmow3574eca2012-10-08 16:38:25 +00009438 unsigned Align = TLI.getDataLayout()->
Owen Anderson23b9b192009-08-12 00:36:31 +00009439 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009440 if (Align <= OrigAlign &&
Duncan Sands25cf2272008-11-24 14:53:14 +00009441 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009442 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009443 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner6229d0a2010-09-21 18:41:36 +00009444 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009445 ST->isNonTemporal(), OrigAlign,
9446 ST->getTBAAInfo());
Jim Laskey279f0532006-09-25 16:29:54 +00009447 }
Owen Andersona34d9362011-04-14 17:30:49 +00009448
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009449 // Turn 'store undef, Ptr' -> nothing.
9450 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9451 return Chain;
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009452
Nate Begeman2cbba892006-12-11 02:23:46 +00009453 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman2cbba892006-12-11 02:23:46 +00009454 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009455 // NOTE: If the original store is volatile, this transform must not increase
9456 // the number of stores. For example, on x86-32 an f64 can be stored in one
9457 // processor operation but an i64 (which is not legal) requires two. So the
9458 // transform should not be done in this case.
Evan Cheng25ece662006-12-11 17:25:19 +00009459 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman475871a2008-07-27 21:46:04 +00009460 SDValue Tmp;
Craig Topper0ff11902013-08-15 02:44:19 +00009461 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009462 default: llvm_unreachable("Unknown FP type");
Pete Cooper438c0402012-06-21 18:00:39 +00009463 case MVT::f16: // We don't do this for these yet.
9464 case MVT::f80:
Owen Anderson825b72b2009-08-11 20:47:22 +00009465 case MVT::f128:
9466 case MVT::ppcf128:
Dale Johannesenc7b21d52007-09-18 18:36:59 +00009467 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009468 case MVT::f32:
Chris Lattner2392ae72010-04-15 04:48:01 +00009469 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009470 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen9d5f4562007-09-12 03:30:33 +00009471 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson825b72b2009-08-11 20:47:22 +00009472 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009473 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009474 Ptr, ST->getMemOperand());
Chris Lattner62be1a72006-12-12 04:16:14 +00009475 }
9476 break;
Owen Anderson825b72b2009-08-11 20:47:22 +00009477 case MVT::f64:
Chris Lattner2392ae72010-04-15 04:48:01 +00009478 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009479 !ST->isVolatile()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +00009480 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen7111b022008-10-09 18:53:47 +00009481 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson825b72b2009-08-11 20:47:22 +00009482 getZExtValue(), MVT::i64);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009483 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009484 Ptr, ST->getMemOperand());
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009485 }
Owen Andersona34d9362011-04-14 17:30:49 +00009486
Chris Lattnerb3452ea2011-04-09 02:32:02 +00009487 if (!ST->isVolatile() &&
9488 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sandsdc846502007-10-28 12:59:45 +00009489 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattner62be1a72006-12-12 04:16:14 +00009490 // argument passing. Since this is so common, custom legalize the
9491 // 64-bit integer store into two 32-bit stores.
Dale Johannesen7111b022008-10-09 18:53:47 +00009492 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson825b72b2009-08-11 20:47:22 +00009493 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9494 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands0753fc12008-02-11 10:37:04 +00009495 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattner62be1a72006-12-12 04:16:14 +00009496
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009497 unsigned Alignment = ST->getAlignment();
9498 bool isVolatile = ST->isVolatile();
David Greene1e559442010-02-15 17:00:31 +00009499 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford66589dc2013-10-28 11:17:59 +00009500 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohmand6fd1bc2007-07-09 22:18:38 +00009501
Andrew Trickac6d9be2013-05-25 02:42:55 +00009502 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009503 Ptr, ST->getPointerInfo(),
David Greene1e559442010-02-15 17:00:31 +00009504 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009505 ST->getAlignment(), TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009506 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattner62be1a72006-12-12 04:16:14 +00009507 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sandsdc846502007-10-28 12:59:45 +00009508 Alignment = MinAlign(Alignment, 4U);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009509 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner6229d0a2010-09-21 18:41:36 +00009510 Ptr, ST->getPointerInfo().getWithOffset(4),
9511 isVolatile, isNonTemporal,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009512 Alignment, TBAAInfo);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009513 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendlingc144a572009-01-30 23:36:47 +00009514 St0, St1);
Chris Lattner62be1a72006-12-12 04:16:14 +00009515 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009516
Chris Lattner62be1a72006-12-12 04:16:14 +00009517 break;
Evan Cheng25ece662006-12-11 17:25:19 +00009518 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009519 }
Nate Begeman2cbba892006-12-11 02:23:46 +00009520 }
9521
Evan Cheng255f20f2010-04-01 06:04:33 +00009522 // Try to infer better alignment information than the store already has.
9523 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Chenged1c0c72011-11-28 22:37:34 +00009524 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9525 if (Align > ST->getAlignment())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009526 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Chenged1c0c72011-11-28 22:37:34 +00009527 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009528 ST->isVolatile(), ST->isNonTemporal(), Align,
9529 ST->getTBAAInfo());
Evan Cheng255f20f2010-04-01 06:04:33 +00009530 }
9531 }
9532
Evan Cheng31959b12011-02-02 01:06:55 +00009533 // Try transforming a pair floating point load / store ops to integer
9534 // load / store ops.
9535 SDValue NewST = TransformFPLoadStorePair(N);
9536 if (NewST.getNode())
9537 return NewST;
9538
Hal Finkel253acef2013-08-29 03:29:55 +00009539 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9540 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -07009541#ifndef NDEBUG
9542 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9543 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9544 UseAA = false;
9545#endif
9546 if (UseAA && ST->isUnindexed()) {
Jim Laskey279f0532006-09-25 16:29:54 +00009547 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman475871a2008-07-27 21:46:04 +00009548 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelfdc40a02009-02-17 22:15:04 +00009549
Jim Laskey6ff23e52006-10-04 16:53:27 +00009550 // If there is a better chain.
Jim Laskey279f0532006-09-25 16:29:54 +00009551 if (Chain != BetterChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00009552 SDValue ReplStore;
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009553
9554 // Replace the chain to avoid dependency.
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009555 if (ST->isTruncatingStore()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009556 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009557 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009558 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009559 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009560 ST->getMemOperand());
Jim Laskeyd4edf2c2006-10-14 12:14:27 +00009561 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009562
Jim Laskey279f0532006-09-25 16:29:54 +00009563 // Create token to keep both nodes around.
Andrew Trickac6d9be2013-05-25 02:42:55 +00009564 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson825b72b2009-08-11 20:47:22 +00009565 MVT::Other, Chain, ReplStore);
Bill Wendlingc144a572009-01-30 23:36:47 +00009566
Nate Begemanb6aef5c2009-09-15 00:18:30 +00009567 // Make sure the new and old chains are cleaned up.
9568 AddToWorkList(Token.getNode());
9569
Jim Laskey274062c2006-10-13 23:32:28 +00009570 // Don't add users to work list.
9571 return CombineTo(N, Token, false);
Jim Laskey279f0532006-09-25 16:29:54 +00009572 }
Jim Laskeyd1aed7a2006-09-21 16:28:59 +00009573 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009574
Evan Cheng33dbedc2006-11-05 09:31:14 +00009575 // Try transforming N to an indexed store.
Evan Chengbbd6f6e2006-11-07 09:03:05 +00009576 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman475871a2008-07-27 21:46:04 +00009577 return SDValue(N, 0);
Evan Cheng33dbedc2006-11-05 09:31:14 +00009578
Chris Lattner3c872852007-12-29 06:26:16 +00009579 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattnerddf89562008-01-17 19:59:44 +00009580 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotembaff46f2011-06-15 11:19:12 +00009581 Value.getValueType().isInteger()) {
Chris Lattner2b4c2792007-10-13 06:35:54 +00009582 // See if we can simplify the input to this truncstore with knowledge that
9583 // only the low bits are being used. For example:
9584 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelfdc40a02009-02-17 22:15:04 +00009585 SDValue Shorter =
Dan Gohman2e68b6f2008-02-25 21:11:39 +00009586 GetDemandedBits(Value,
Nadav Rotembaff46f2011-06-15 11:19:12 +00009587 APInt::getLowBitsSet(
9588 Value.getValueType().getScalarType().getSizeInBits(),
9589 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greifba36cb52008-08-28 21:40:38 +00009590 AddToWorkList(Value.getNode());
9591 if (Shorter.getNode())
Andrew Trickac6d9be2013-05-25 02:42:55 +00009592 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford66589dc2013-10-28 11:17:59 +00009593 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelfdc40a02009-02-17 22:15:04 +00009594
Chris Lattnere33544c2007-10-13 06:58:48 +00009595 // Otherwise, see if we can simplify the operation with
9596 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman7b8d4a92008-02-27 00:25:32 +00009597 if (SimplifyDemandedBits(Value,
Eric Christopher503a64d2010-12-09 04:48:06 +00009598 APInt::getLowBitsSet(
9599 Value.getValueType().getScalarType().getSizeInBits(),
9600 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman475871a2008-07-27 21:46:04 +00009601 return SDValue(N, 0);
Chris Lattner2b4c2792007-10-13 06:35:54 +00009602 }
Scott Michelfdc40a02009-02-17 22:15:04 +00009603
Chris Lattner3c872852007-12-29 06:26:16 +00009604 // If this is a load followed by a store to the same location, then the store
9605 // is dead/noop.
9606 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009607 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009608 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner07649d92008-01-08 23:08:06 +00009609 // There can't be any side effects between the load and store, such as
9610 // a call or store.
Dan Gohman475871a2008-07-27 21:46:04 +00009611 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3c872852007-12-29 06:26:16 +00009612 // The store is dead, remove it.
9613 return Chain;
9614 }
9615 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009616
Chris Lattnerddf89562008-01-17 19:59:44 +00009617 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9618 // truncating store. We can do this even if this is already a truncstore.
9619 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greifba36cb52008-08-28 21:40:38 +00009620 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattnerddf89562008-01-17 19:59:44 +00009621 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohmanb625f2f2008-01-30 00:15:11 +00009622 ST->getMemoryVT())) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009623 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009624 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattnerddf89562008-01-17 19:59:44 +00009625 }
Duncan Sandsd4b9c172008-06-13 19:07:40 +00009626
Nadav Rotemc653de62012-10-03 16:11:15 +00009627 // Only perform this optimization before the types are legal, because we
Nadav Rotemea2c50c2012-10-04 22:35:15 +00009628 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotema569a802012-12-02 17:14:09 +00009629 if (!LegalTypes) {
9630 bool EverChanged = false;
9631
9632 do {
9633 // There can be multiple store sequences on the same chain.
9634 // Keep trying to merge store sequences until we are unable to do so
9635 // or until we merge the last store on the chain.
9636 bool Changed = MergeConsecutiveStores(ST);
9637 EverChanged |= Changed;
9638 if (!Changed) break;
9639 } while (ST->getOpcode() != ISD::DELETED_NODE);
9640
9641 if (EverChanged)
9642 return SDValue(N, 0);
9643 }
Nadav Rotemc653de62012-10-03 16:11:15 +00009644
Evan Cheng8b944d32009-05-28 00:35:15 +00009645 return ReduceLoadOpStoreWidth(N);
Chris Lattner87514ca2005-10-10 22:31:19 +00009646}
9647
Dan Gohman475871a2008-07-27 21:46:04 +00009648SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9649 SDValue InVec = N->getOperand(0);
9650 SDValue InVal = N->getOperand(1);
9651 SDValue EltNo = N->getOperand(2);
Andrew Trickac6d9be2013-05-25 02:42:55 +00009652 SDLoc dl(N);
Scott Michelfdc40a02009-02-17 22:15:04 +00009653
Bob Wilson492fd452010-05-19 23:42:58 +00009654 // If the inserted element is an UNDEF, just use the input vector.
9655 if (InVal.getOpcode() == ISD::UNDEF)
9656 return InVec;
9657
Nadav Rotem609d54e2011-02-12 14:40:33 +00009658 EVT VT = InVec.getValueType();
9659
Owen Anderson95771af2011-02-25 21:41:48 +00009660 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotem609d54e2011-02-12 14:40:33 +00009661 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9662 return SDValue();
9663
Eli Friedman9db817f2011-09-09 21:04:06 +00009664 // Check that we know which element is being inserted
9665 if (!isa<ConstantSDNode>(EltNo))
9666 return SDValue();
9667 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelfdc40a02009-02-17 22:15:04 +00009668
Eli Friedman9db817f2011-09-09 21:04:06 +00009669 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9670 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9671 // vector elements.
9672 SmallVector<SDValue, 8> Ops;
Quentin Colombet75c94332013-07-30 00:24:09 +00009673 // Do not combine these two vectors if the output vector will not replace
9674 // the input vector.
9675 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedman9db817f2011-09-09 21:04:06 +00009676 Ops.append(InVec.getNode()->op_begin(),
9677 InVec.getNode()->op_end());
9678 } else if (InVec.getOpcode() == ISD::UNDEF) {
9679 unsigned NElts = VT.getVectorNumElements();
9680 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9681 } else {
9682 return SDValue();
Nate Begeman9008ca62009-04-27 18:41:29 +00009683 }
Eli Friedman9db817f2011-09-09 21:04:06 +00009684
9685 // Insert the element
9686 if (Elt < Ops.size()) {
9687 // All the operands of BUILD_VECTOR must have the same type;
9688 // we enforce that here.
9689 EVT OpVT = Ops[0].getValueType();
9690 if (InVal.getValueType() != OpVT)
9691 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9692 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9693 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9694 Ops[Elt] = InVal;
9695 }
9696
9697 // Return the new vector
Stephen Hinesdce4a402014-05-29 02:49:00 -07009698 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattnerca242442006-03-19 01:27:56 +00009699}
9700
Dan Gohman475871a2008-07-27 21:46:04 +00009701SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009702 // (vextract (scalar_to_vector val, 0) -> val
9703 SDValue InVec = N->getOperand(0);
Nadav Rotemba05c912012-01-17 21:44:01 +00009704 EVT VT = InVec.getValueType();
9705 EVT NVT = N->getValueType(0);
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009706
Duncan Sandsc356f332011-05-09 08:03:33 +00009707 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9708 // Check if the result type doesn't match the inserted element type. A
9709 // SCALAR_TO_VECTOR may truncate the inserted element and the
9710 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9711 SDValue InOp = InVec.getOperand(0);
Duncan Sandsc356f332011-05-09 08:03:33 +00009712 if (InOp.getValueType() != NVT) {
9713 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickac6d9be2013-05-25 02:42:55 +00009714 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sandsc356f332011-05-09 08:03:33 +00009715 }
9716 return InOp;
9717 }
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009718
Nadav Rotemba05c912012-01-17 21:44:01 +00009719 SDValue EltNo = N->getOperand(1);
9720 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9721
9722 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9723 // We only perform this optimization before the op legalization phase because
Nadav Rotem6dfabb62012-09-20 08:53:31 +00009724 // we may introduce new vector instructions which are not backed by TD
9725 // patterns. For example on AVX, extracting elements from a wide vector
Stephen Hines36b56882014-04-23 16:57:46 -07009726 // without using extract_subvector. However, if we can find an underlying
9727 // scalar value, then we can always use that.
Nadav Rotemba05c912012-01-17 21:44:01 +00009728 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Stephen Hines36b56882014-04-23 16:57:46 -07009729 && ConstEltNo) {
Nadav Rotemba05c912012-01-17 21:44:01 +00009730 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9731 int NumElem = VT.getVectorNumElements();
9732 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9733 // Find the new index to extract from.
9734 int OrigElt = SVOp->getMaskElt(Elt);
9735
9736 // Extracting an undef index is undef.
9737 if (OrigElt == -1)
9738 return DAG.getUNDEF(NVT);
9739
9740 // Select the right vector half to extract from.
Stephen Hines36b56882014-04-23 16:57:46 -07009741 SDValue SVInVec;
Nadav Rotemba05c912012-01-17 21:44:01 +00009742 if (OrigElt < NumElem) {
Stephen Hines36b56882014-04-23 16:57:46 -07009743 SVInVec = InVec->getOperand(0);
Nadav Rotemba05c912012-01-17 21:44:01 +00009744 } else {
Stephen Hines36b56882014-04-23 16:57:46 -07009745 SVInVec = InVec->getOperand(1);
Nadav Rotemba05c912012-01-17 21:44:01 +00009746 OrigElt -= NumElem;
9747 }
9748
Stephen Hines36b56882014-04-23 16:57:46 -07009749 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9750 SDValue InOp = SVInVec.getOperand(OrigElt);
9751 if (InOp.getValueType() != NVT) {
9752 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9753 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9754 }
9755
9756 return InOp;
9757 }
9758
9759 // FIXME: We should handle recursing on other vector shuffles and
9760 // scalar_to_vector here as well.
9761
9762 if (!LegalOperations) {
9763 EVT IndexTy = TLI.getVectorIdxTy();
9764 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9765 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9766 }
Nadav Rotemba05c912012-01-17 21:44:01 +00009767 }
9768
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009769 // Perform only after legalization to ensure build_vector / vector_shuffle
9770 // optimizations have already been done.
Duncan Sands25cf2272008-11-24 14:53:14 +00009771 if (!LegalOperations) return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009772
Mon P Wang7ac9cdf2009-01-17 00:07:25 +00009773 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9774 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9775 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng513da432007-10-06 08:19:55 +00009776
Nadav Rotemba05c912012-01-17 21:44:01 +00009777 if (ConstEltNo) {
Eric Christophercaebdd42010-11-03 09:36:40 +00009778 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng513da432007-10-06 08:19:55 +00009779 bool NewLoad = false;
Mon P Wanga60b5232008-12-11 00:26:16 +00009780 bool BCNumEltsChanged = false;
Owen Andersone50ed302009-08-10 22:56:29 +00009781 EVT ExtVT = VT.getVectorElementType();
9782 EVT LVT = ExtVT;
Bill Wendlingc144a572009-01-30 23:36:47 +00009783
Evan Cheng84387ea2012-03-13 22:00:52 +00009784 // If the result of load has to be truncated, then it's not necessarily
9785 // profitable.
Evan Chenga03d3662012-03-13 22:16:11 +00009786 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng84387ea2012-03-13 22:00:52 +00009787 return SDValue();
9788
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009789 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009790 // Don't duplicate a load with other uses.
9791 if (!InVec.hasOneUse())
9792 return SDValue();
9793
Owen Andersone50ed302009-08-10 22:56:29 +00009794 EVT BCVT = InVec.getOperand(0).getValueType();
9795 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman475871a2008-07-27 21:46:04 +00009796 return SDValue();
Mon P Wanga60b5232008-12-11 00:26:16 +00009797 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9798 BCNumEltsChanged = true;
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009799 InVec = InVec.getOperand(0);
Owen Andersone50ed302009-08-10 22:56:29 +00009800 ExtVT = BCVT.getVectorElementType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009801 NewLoad = true;
9802 }
Evan Cheng513da432007-10-06 08:19:55 +00009803
Stephen Hinesdce4a402014-05-29 02:49:00 -07009804 LoadSDNode *LN0 = nullptr;
9805 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendlingc144a572009-01-30 23:36:47 +00009806 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009807 LN0 = cast<LoadSDNode>(InVec);
Bill Wendlingc144a572009-01-30 23:36:47 +00009808 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Andersone50ed302009-08-10 22:56:29 +00009809 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendlingc144a572009-01-30 23:36:47 +00009810 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmand6e25602011-12-26 22:49:32 +00009811 // Don't duplicate a load with other uses.
9812 if (!InVec.hasOneUse())
9813 return SDValue();
9814
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009815 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5a5ca152009-04-29 05:20:52 +00009816 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009817 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9818 // =>
9819 // (load $addr+1*size)
Scott Michelfdc40a02009-02-17 22:15:04 +00009820
Eli Friedmand6e25602011-12-26 22:49:32 +00009821 // Don't duplicate a load with other uses.
9822 if (!InVec.hasOneUse())
9823 return SDValue();
9824
Mon P Wanga60b5232008-12-11 00:26:16 +00009825 // If the bit convert changed the number of elements, it is unsafe
9826 // to examine the mask.
9827 if (BCNumEltsChanged)
9828 return SDValue();
Nate Begeman5a5ca152009-04-29 05:20:52 +00009829
9830 // Select the input vector, guarding against out of range extract vector.
9831 unsigned NumElems = VT.getVectorNumElements();
Eric Christophercaebdd42010-11-03 09:36:40 +00009832 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5a5ca152009-04-29 05:20:52 +00009833 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9834
Eli Friedmand6e25602011-12-26 22:49:32 +00009835 if (InVec.getOpcode() == ISD::BITCAST) {
9836 // Don't duplicate a load with other uses.
9837 if (!InVec.hasOneUse())
9838 return SDValue();
9839
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009840 InVec = InVec.getOperand(0);
Eli Friedmand6e25602011-12-26 22:49:32 +00009841 }
Gabor Greifba36cb52008-08-28 21:40:38 +00009842 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009843 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd0e88f32010-04-08 18:49:30 +00009844 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng513da432007-10-06 08:19:55 +00009845 }
9846 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009847
Eli Friedmand6e25602011-12-26 22:49:32 +00009848 // Make sure we found a non-volatile load and the extractelement is
9849 // the only use.
Nadav Rotem42febc62011-05-11 14:40:50 +00009850 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman475871a2008-07-27 21:46:04 +00009851 return SDValue();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009852
Eric Christopherd81f17a2010-11-03 20:44:42 +00009853 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9854 if (Elt == -1)
Eli Friedmaned4b4272011-07-25 22:25:42 +00009855 return DAG.getUNDEF(LVT);
Eric Christopherd81f17a2010-11-03 20:44:42 +00009856
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009857 unsigned Align = LN0->getAlignment();
9858 if (NewLoad) {
9859 // Check the resultant load doesn't need a higher alignment than the
9860 // original load.
Bill Wendlingc144a572009-01-30 23:36:47 +00009861 unsigned NewAlign =
Micah Villmow3574eca2012-10-08 16:38:25 +00009862 TLI.getDataLayout()
Eric Christopher503a64d2010-12-09 04:48:06 +00009863 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendlingc144a572009-01-30 23:36:47 +00009864
Dan Gohmanf560ffa2009-01-28 17:46:25 +00009865 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman475871a2008-07-27 21:46:04 +00009866 return SDValue();
Bill Wendlingc144a572009-01-30 23:36:47 +00009867
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009868 Align = NewAlign;
9869 }
9870
Dan Gohman475871a2008-07-27 21:46:04 +00009871 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerfa459012010-09-21 16:08:50 +00009872 unsigned PtrOff = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +00009873
Eric Christopherd81f17a2010-11-03 20:44:42 +00009874 if (Elt) {
Chris Lattnerfa459012010-09-21 16:08:50 +00009875 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Andersone50ed302009-08-10 22:56:29 +00009876 EVT PtrType = NewPtr.getValueType();
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009877 if (TLI.isBigEndian())
Duncan Sands83ec4b62008-06-06 12:08:01 +00009878 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009879 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng77f0b7a2008-05-13 08:35:03 +00009880 DAG.getConstant(PtrOff, PtrType));
9881 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009882
Eli Friedman4db4add2011-11-16 23:50:22 +00009883 // The replacement we need to do here is a little tricky: we need to
9884 // replace an extractelement of a load with a load.
9885 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmand6e25602011-12-26 22:49:32 +00009886 // Note that this replacement assumes that the extractvalue is the only
9887 // use of the load; that's okay because we don't want to perform this
9888 // transformation in other cases anyway.
Evan Cheng84387ea2012-03-13 22:00:52 +00009889 SDValue Load;
Evan Chenga03d3662012-03-13 22:16:11 +00009890 SDValue Chain;
Evan Cheng84387ea2012-03-13 22:00:52 +00009891 if (NVT.bitsGT(LVT)) {
9892 // If the result type of vextract is wider than the load, then issue an
9893 // extending load instead.
9894 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9895 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickac6d9be2013-05-25 02:42:55 +00009896 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng84387ea2012-03-13 22:00:52 +00009897 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009898 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9899 Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009900 Chain = Load.getValue(1);
9901 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00009902 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng84387ea2012-03-13 22:00:52 +00009903 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lin155615d2013-07-08 00:37:03 +00009904 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford66589dc2013-10-28 11:17:59 +00009905 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chenga03d3662012-03-13 22:16:11 +00009906 Chain = Load.getValue(1);
9907 if (NVT.bitsLT(LVT))
Andrew Trickac6d9be2013-05-25 02:42:55 +00009908 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009909 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00009910 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chenga03d3662012-03-13 22:16:11 +00009911 }
Eli Friedman4db4add2011-11-16 23:50:22 +00009912 WorkListRemover DeadNodes(*this);
9913 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chenga03d3662012-03-13 22:16:11 +00009914 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbc7d4482012-04-20 22:08:46 +00009915 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedman4db4add2011-11-16 23:50:22 +00009916 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9917 // worklist explicitly as well.
9918 AddToWorkList(Load.getNode());
Craig Topper0c9da212012-03-20 05:28:39 +00009919 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedman4db4add2011-11-16 23:50:22 +00009920 // Make sure to revisit this node to clean it up; it will usually be dead.
9921 AddToWorkList(N);
9922 return SDValue(N, 0);
Evan Cheng513da432007-10-06 08:19:55 +00009923 }
Bill Wendlingc144a572009-01-30 23:36:47 +00009924
Dan Gohman475871a2008-07-27 21:46:04 +00009925 return SDValue();
Evan Cheng513da432007-10-06 08:19:55 +00009926}
Evan Cheng513da432007-10-06 08:19:55 +00009927
Michael Liaofac14ab2012-10-23 23:06:52 +00009928// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9929SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9930 // We perform this optimization post type-legalization because
9931 // the type-legalizer often scalarizes integer-promoted vectors.
9932 // Performing this optimization before may create bit-casts which
9933 // will be type-legalized to complex code sequences.
9934 // We perform this optimization only before the operation legalizer because we
9935 // may introduce illegal operations.
9936 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9937 return SDValue();
9938
Dan Gohman7f321562007-06-25 16:23:39 +00009939 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +00009940 SDLoc dl(N);
Owen Andersone50ed302009-08-10 22:56:29 +00009941 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009942
Nadav Rotemb00418a2011-10-29 21:23:04 +00009943 // Check to see if this is a BUILD_VECTOR of a bunch of values
9944 // which come from any_extend or zero_extend nodes. If so, we can create
9945 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf47368b2011-10-31 20:08:25 +00009946 // optimizations. We do not handle sign-extend because we can't fill the sign
9947 // using shuffles.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009948 EVT SourceType = MVT::Other;
Craig Topperd3b58892012-01-17 09:09:48 +00009949 bool AllAnyExt = true;
Nadav Rotemb87bdac2012-07-15 08:38:23 +00009950
Craig Topperd3b58892012-01-17 09:09:48 +00009951 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotemb00418a2011-10-29 21:23:04 +00009952 SDValue In = N->getOperand(i);
9953 // Ignore undef inputs.
9954 if (In.getOpcode() == ISD::UNDEF) continue;
9955
9956 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9957 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9958
Nadav Rotemf47368b2011-10-31 20:08:25 +00009959 // Abort if the element is not an extension.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009960 if (!ZeroExt && !AnyExt) {
Nadav Rotemf47368b2011-10-31 20:08:25 +00009961 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009962 break;
9963 }
9964
9965 // The input is a ZeroExt or AnyExt. Check the original type.
9966 EVT InTy = In.getOperand(0).getValueType();
9967
9968 // Check that all of the widened source types are the same.
9969 if (SourceType == MVT::Other)
Nadav Rotemf47368b2011-10-31 20:08:25 +00009970 // First time.
Nadav Rotemb00418a2011-10-29 21:23:04 +00009971 SourceType = InTy;
9972 else if (InTy != SourceType) {
9973 // Multiple income types. Abort.
Nadav Rotemf47368b2011-10-31 20:08:25 +00009974 SourceType = MVT::Other;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009975 break;
9976 }
9977
9978 // Check if all of the extends are ANY_EXTENDs.
Craig Topperd3b58892012-01-17 09:09:48 +00009979 AllAnyExt &= AnyExt;
Nadav Rotemb00418a2011-10-29 21:23:04 +00009980 }
9981
Nadav Rotemf47368b2011-10-31 20:08:25 +00009982 // In order to have valid types, all of the inputs must be extended from the
9983 // same source type and all of the inputs must be any or zero extend.
9984 // Scalar sizes must be a power of two.
Michael Liaofac14ab2012-10-23 23:06:52 +00009985 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem2ee746b2012-02-12 15:05:31 +00009986 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf47368b2011-10-31 20:08:25 +00009987 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9988 isPowerOf2_32(SourceType.getSizeInBits());
9989
Nadav Rotem6431ff92012-03-15 08:49:06 +00009990 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9991 // turn into a single shuffle instruction.
Michael Liaofac14ab2012-10-23 23:06:52 +00009992 if (!ValidTypes)
9993 return SDValue();
Nadav Rotemb00418a2011-10-29 21:23:04 +00009994
Michael Liaofac14ab2012-10-23 23:06:52 +00009995 bool isLE = TLI.isLittleEndian();
9996 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9997 assert(ElemRatio > 1 && "Invalid element size ratio");
9998 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9999 DAG.getConstant(0, SourceType);
Nadav Rotemb00418a2011-10-29 21:23:04 +000010000
Michael Liaofac14ab2012-10-23 23:06:52 +000010001 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10002 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotemb00418a2011-10-29 21:23:04 +000010003
Michael Liaofac14ab2012-10-23 23:06:52 +000010004 // Populate the new build_vector
Jakub Staszakadf38912012-10-24 00:38:25 +000010005 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liaofac14ab2012-10-23 23:06:52 +000010006 SDValue Cast = N->getOperand(i);
10007 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10008 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10009 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10010 SDValue In;
10011 if (Cast.getOpcode() == ISD::UNDEF)
10012 In = DAG.getUNDEF(SourceType);
10013 else
10014 In = Cast->getOperand(0);
10015 unsigned Index = isLE ? (i * ElemRatio) :
10016 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotemb00418a2011-10-29 21:23:04 +000010017
Michael Liaofac14ab2012-10-23 23:06:52 +000010018 assert(Index < Ops.size() && "Invalid index");
10019 Ops[Index] = In;
Nadav Rotemb00418a2011-10-29 21:23:04 +000010020 }
Chris Lattnerca242442006-03-19 01:27:56 +000010021
Michael Liaofac14ab2012-10-23 23:06:52 +000010022 // The type of the new BUILD_VECTOR node.
10023 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10024 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10025 "Invalid vector size");
10026 // Check if the new vector type is legal.
10027 if (!isTypeLegal(VecVT)) return SDValue();
10028
10029 // Make the new BUILD_VECTOR.
Stephen Hinesdce4a402014-05-29 02:49:00 -070010030 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liaofac14ab2012-10-23 23:06:52 +000010031
10032 // The new BUILD_VECTOR node has the potential to be further optimized.
10033 AddToWorkList(BV.getNode());
10034 // Bitcast to the desired type.
10035 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10036}
10037
Michael Liao1a5cc712012-10-24 04:14:18 +000010038SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10039 EVT VT = N->getValueType(0);
10040
10041 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010042 SDLoc dl(N);
Michael Liao1a5cc712012-10-24 04:14:18 +000010043
10044 EVT SrcVT = MVT::Other;
10045 unsigned Opcode = ISD::DELETED_NODE;
10046 unsigned NumDefs = 0;
10047
10048 for (unsigned i = 0; i != NumInScalars; ++i) {
10049 SDValue In = N->getOperand(i);
10050 unsigned Opc = In.getOpcode();
10051
10052 if (Opc == ISD::UNDEF)
10053 continue;
10054
10055 // If all scalar values are floats and converted from integers.
10056 if (Opcode == ISD::DELETED_NODE &&
10057 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10058 Opcode = Opc;
Michael Liao1a5cc712012-10-24 04:14:18 +000010059 }
Tom Stellardd40758b2013-01-02 22:13:01 +000010060
Michael Liao1a5cc712012-10-24 04:14:18 +000010061 if (Opc != Opcode)
10062 return SDValue();
10063
10064 EVT InVT = In.getOperand(0).getValueType();
10065
10066 // If all scalar values are typed differently, bail out. It's chosen to
10067 // simplify BUILD_VECTOR of integer types.
10068 if (SrcVT == MVT::Other)
10069 SrcVT = InVT;
10070 if (SrcVT != InVT)
10071 return SDValue();
10072 NumDefs++;
10073 }
10074
10075 // If the vector has just one element defined, it's not worth to fold it into
10076 // a vectorized one.
10077 if (NumDefs < 2)
10078 return SDValue();
10079
10080 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10081 && "Should only handle conversion from integer to float.");
10082 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10083
10084 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellardd40758b2013-01-02 22:13:01 +000010085
10086 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10087 return SDValue();
10088
Michael Liao1a5cc712012-10-24 04:14:18 +000010089 SmallVector<SDValue, 8> Opnds;
10090 for (unsigned i = 0; i != NumInScalars; ++i) {
10091 SDValue In = N->getOperand(i);
10092
10093 if (In.getOpcode() == ISD::UNDEF)
10094 Opnds.push_back(DAG.getUNDEF(SrcVT));
10095 else
10096 Opnds.push_back(In.getOperand(0));
10097 }
Stephen Hinesdce4a402014-05-29 02:49:00 -070010098 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Michael Liao1a5cc712012-10-24 04:14:18 +000010099 AddToWorkList(BV.getNode());
10100
10101 return DAG.getNode(Opcode, dl, VT, BV);
10102}
10103
Michael Liaofac14ab2012-10-23 23:06:52 +000010104SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10105 unsigned NumInScalars = N->getNumOperands();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010106 SDLoc dl(N);
Michael Liaofac14ab2012-10-23 23:06:52 +000010107 EVT VT = N->getValueType(0);
10108
10109 // A vector built entirely of undefs is undef.
10110 if (ISD::allOperandsUndef(N))
10111 return DAG.getUNDEF(VT);
10112
10113 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10114 if (V.getNode())
10115 return V;
10116
Michael Liao1a5cc712012-10-24 04:14:18 +000010117 V = reduceBuildVecConvertToConvertBuildVec(N);
10118 if (V.getNode())
10119 return V;
10120
Dan Gohman7f321562007-06-25 16:23:39 +000010121 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10122 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10123 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands00294ca2012-03-19 15:35:44 +000010124
10125 // May only combine to shuffle after legalize if shuffle is legal.
10126 if (LegalOperations &&
10127 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10128 return SDValue();
10129
Dan Gohman475871a2008-07-27 21:46:04 +000010130 SDValue VecIn1, VecIn2;
Chris Lattnerd7648c82006-03-28 20:28:38 +000010131 for (unsigned i = 0; i != NumInScalars; ++i) {
10132 // Ignore undef inputs.
10133 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000010134
Dan Gohman7f321562007-06-25 16:23:39 +000010135 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerd7648c82006-03-28 20:28:38 +000010136 // constant index, bail out.
Dan Gohman7f321562007-06-25 16:23:39 +000010137 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerd7648c82006-03-28 20:28:38 +000010138 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Stephen Hinesdce4a402014-05-29 02:49:00 -070010139 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010140 break;
10141 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010142
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010143 // We allow up to two distinct input vectors.
Dan Gohman475871a2008-07-27 21:46:04 +000010144 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010145 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10146 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000010147
Stephen Hinesdce4a402014-05-29 02:49:00 -070010148 if (!VecIn1.getNode()) {
Chris Lattnerd7648c82006-03-28 20:28:38 +000010149 VecIn1 = ExtractedFromVec;
Stephen Hinesdce4a402014-05-29 02:49:00 -070010150 } else if (!VecIn2.getNode()) {
Chris Lattnerd7648c82006-03-28 20:28:38 +000010151 VecIn2 = ExtractedFromVec;
10152 } else {
10153 // Too many inputs.
Stephen Hinesdce4a402014-05-29 02:49:00 -070010154 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010155 break;
10156 }
10157 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010158
Stephen Hinesdce4a402014-05-29 02:49:00 -070010159 // If everything is good, we can make a shuffle operation.
Gabor Greifba36cb52008-08-28 21:40:38 +000010160 if (VecIn1.getNode()) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010161 SmallVector<int, 8> Mask;
Chris Lattnerd7648c82006-03-28 20:28:38 +000010162 for (unsigned i = 0; i != NumInScalars; ++i) {
10163 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010164 Mask.push_back(-1);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010165 continue;
10166 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010167
Rafael Espindola15684b22009-04-24 12:40:33 +000010168 // If extracting from the first vector, just use the index directly.
Nate Begeman9008ca62009-04-27 18:41:29 +000010169 SDValue Extract = N->getOperand(i);
Mon P Wang93b74152009-03-17 06:33:10 +000010170 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010171 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5a5ca152009-04-29 05:20:52 +000010172 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10173 if (ExtIndex > VT.getVectorNumElements())
10174 return SDValue();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010175
Nate Begeman5a5ca152009-04-29 05:20:52 +000010176 Mask.push_back(ExtIndex);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010177 continue;
10178 }
10179
10180 // Otherwise, use InIdx + VecSize
Mon P Wang93b74152009-03-17 06:33:10 +000010181 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman9008ca62009-04-27 18:41:29 +000010182 Mask.push_back(Idx+NumInScalars);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010183 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010184
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010185 // We can't generate a shuffle node with mismatched input and output types.
10186 // Attempt to transform a single input vector to the correct type.
10187 if ((VT != VecIn1.getValueType())) {
10188 // We don't support shuffeling between TWO values of different types.
Stephen Hinesdce4a402014-05-29 02:49:00 -070010189 if (VecIn2.getNode())
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010190 return SDValue();
10191
10192 // We only support widening of vectors which are half the size of the
10193 // output registers. For example XMM->YMM widening on X86 with AVX.
10194 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10195 return SDValue();
10196
James Molloy8cd08bf2012-09-10 14:01:21 +000010197 // If the input vector type has a different base type to the output
10198 // vector type, bail out.
10199 if (VecIn1.getValueType().getVectorElementType() !=
10200 VT.getVectorElementType())
10201 return SDValue();
10202
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +000010203 // Widen the input vector by adding undef values.
Michael Liaofac14ab2012-10-23 23:06:52 +000010204 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiyfdeb9fe2012-08-22 09:33:55 +000010205 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010206 }
10207
10208 // If VecIn2 is unused then change it to undef.
10209 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10210
Nadav Rotem6dfabb62012-09-20 08:53:31 +000010211 // Check that we were able to transform all incoming values to the same
10212 // type.
Nadav Rotem0877fdf2012-02-13 12:42:26 +000010213 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10214 VecIn1.getValueType() != VT)
10215 return SDValue();
10216
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010217 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0877fdf2012-02-13 12:42:26 +000010218 if (!isTypeLegal(VT))
Duncan Sands25cf2272008-11-24 14:53:14 +000010219 return SDValue();
10220
Dan Gohman7f321562007-06-25 16:23:39 +000010221 // Return the new VECTOR_SHUFFLE node.
Nate Begeman9008ca62009-04-27 18:41:29 +000010222 SDValue Ops[2];
Chris Lattnerbd564bf2006-08-08 02:23:42 +000010223 Ops[0] = VecIn1;
Nadav Rotem2ee746b2012-02-12 15:05:31 +000010224 Ops[1] = VecIn2;
Michael Liaofac14ab2012-10-23 23:06:52 +000010225 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerd7648c82006-03-28 20:28:38 +000010226 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010227
Dan Gohman475871a2008-07-27 21:46:04 +000010228 return SDValue();
Chris Lattnerd7648c82006-03-28 20:28:38 +000010229}
10230
Dan Gohman475871a2008-07-27 21:46:04 +000010231SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohman7f321562007-06-25 16:23:39 +000010232 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10233 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10234 // inputs come from at most two distinct vectors, turn this into a shuffle
10235 // node.
10236
10237 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendlingc144a572009-01-30 23:36:47 +000010238 if (N->getNumOperands() == 1)
Dan Gohman7f321562007-06-25 16:23:39 +000010239 return N->getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +000010240
Nadav Rotemb7e230d2012-07-14 21:30:27 +000010241 // Check if all of the operands are undefs.
Nadav Rotem97541d42013-10-25 06:41:18 +000010242 EVT VT = N->getValueType(0);
Nadav Rotemb87bdac2012-07-15 08:38:23 +000010243 if (ISD::allOperandsUndef(N))
Nadav Rotem97541d42013-10-25 06:41:18 +000010244 return DAG.getUNDEF(VT);
10245
10246 // Optimize concat_vectors where one of the vectors is undef.
10247 if (N->getNumOperands() == 2 &&
10248 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10249 SDValue In = N->getOperand(0);
Bill Wendlingb1eb9dd2013-12-10 06:42:24 +000010250 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotem97541d42013-10-25 06:41:18 +000010251
10252 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10253 if (In->getOpcode() == ISD::BITCAST &&
10254 !In->getOperand(0)->getValueType(0).isVector()) {
10255 SDValue Scalar = In->getOperand(0);
10256 EVT SclTy = Scalar->getValueType(0);
10257
10258 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10259 return SDValue();
10260
10261 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10262 VT.getSizeInBits() / SclTy.getSizeInBits());
10263 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10264 return SDValue();
10265
10266 SDLoc dl = SDLoc(N);
10267 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10268 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10269 }
10270 }
Nadav Rotemb7e230d2012-07-14 21:30:27 +000010271
Stephen Hines36b56882014-04-23 16:57:46 -070010272 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10273 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10274 if (N->getNumOperands() == 2 &&
10275 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10276 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10277 EVT VT = N->getValueType(0);
10278 SDValue N0 = N->getOperand(0);
10279 SDValue N1 = N->getOperand(1);
10280 SmallVector<SDValue, 8> Opnds;
10281 unsigned BuildVecNumElts = N0.getNumOperands();
10282
10283 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10284 Opnds.push_back(N0.getOperand(i));
10285 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10286 Opnds.push_back(N1.getOperand(i));
10287
Stephen Hinesdce4a402014-05-29 02:49:00 -070010288 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Stephen Hines36b56882014-04-23 16:57:46 -070010289 }
10290
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010291 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10292 // nodes often generate nop CONCAT_VECTOR nodes.
10293 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10294 // place the incoming vectors at the exact same location.
10295 SDValue SingleSource = SDValue();
10296 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10297
10298 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10299 SDValue Op = N->getOperand(i);
10300
10301 if (Op.getOpcode() == ISD::UNDEF)
10302 continue;
10303
10304 // Check if this is the identity extract:
10305 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10306 return SDValue();
10307
10308 // Find the single incoming vector for the extract_subvector.
10309 if (SingleSource.getNode()) {
10310 if (Op.getOperand(0) != SingleSource)
10311 return SDValue();
10312 } else {
10313 SingleSource = Op.getOperand(0);
Michael Kuperstein27202482013-05-06 08:06:13 +000010314
10315 // Check the source type is the same as the type of the result.
10316 // If not, this concat may extend the vector, so we can not
10317 // optimize it away.
10318 if (SingleSource.getValueType() != N->getValueType(0))
10319 return SDValue();
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010320 }
10321
10322 unsigned IdentityIndex = i * PartNumElem;
10323 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10324 // The extract index must be constant.
10325 if (!CS)
10326 return SDValue();
Stephen Lin155615d2013-07-08 00:37:03 +000010327
Nadav Rotemb2ed5fa2013-05-01 19:18:51 +000010328 // Check that we are reading from the identity index.
10329 if (CS->getZExtValue() != IdentityIndex)
10330 return SDValue();
10331 }
10332
10333 if (SingleSource.getNode())
10334 return SingleSource;
Stephen Lin155615d2013-07-08 00:37:03 +000010335
Dan Gohman475871a2008-07-27 21:46:04 +000010336 return SDValue();
Dan Gohman7f321562007-06-25 16:23:39 +000010337}
10338
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +000010339SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10340 EVT NVT = N->getValueType(0);
10341 SDValue V = N->getOperand(0);
10342
Michael Liao13429e22012-10-17 20:48:33 +000010343 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10344 // Combine:
10345 // (extract_subvec (concat V1, V2, ...), i)
10346 // Into:
10347 // Vi if possible
Jack Carteradbd3ae2013-10-17 01:34:33 +000010348 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10349 // type.
Michael Liao9aecdb52012-10-19 03:17:00 +000010350 if (V->getOperand(0).getValueType() != NVT)
10351 return SDValue();
Michael Liao13429e22012-10-17 20:48:33 +000010352 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10353 unsigned NumElems = NVT.getVectorNumElements();
10354 assert((Idx % NumElems) == 0 &&
10355 "IDX in concat is not a multiple of the result vector length.");
10356 return V->getOperand(Idx / NumElems);
10357 }
10358
Michael Liaob4f98ea2013-03-25 23:47:35 +000010359 // Skip bitcasting
10360 if (V->getOpcode() == ISD::BITCAST)
10361 V = V.getOperand(0);
10362
10363 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010364 SDLoc dl(N);
Michael Liaob4f98ea2013-03-25 23:47:35 +000010365 // Handle only simple case where vector being inserted and vector
10366 // being extracted are of same type, and are half size of larger vectors.
10367 EVT BigVT = V->getOperand(0).getValueType();
10368 EVT SmallVT = V->getOperand(1).getValueType();
10369 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10370 return SDValue();
10371
10372 // Only handle cases where both indexes are constants with the same type.
10373 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10374 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10375
10376 if (InsIdx && ExtIdx &&
10377 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10378 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10379 // Combine:
10380 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10381 // Into:
10382 // indices are equal or bit offsets are equal => V1
10383 // otherwise => (extract_subvec V1, ExtIdx)
10384 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10385 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10386 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10387 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10388 DAG.getNode(ISD::BITCAST, dl,
10389 N->getOperand(0).getValueType(),
10390 V->getOperand(0)), N->getOperand(1));
10391 }
10392 }
10393
Bruno Cardoso Lopese97190f2011-09-20 23:19:33 +000010394 return SDValue();
10395}
10396
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010397// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10398static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10399 EVT VT = N->getValueType(0);
10400 unsigned NumElts = VT.getVectorNumElements();
10401
10402 SDValue N0 = N->getOperand(0);
10403 SDValue N1 = N->getOperand(1);
10404 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10405
10406 SmallVector<SDValue, 4> Ops;
10407 EVT ConcatVT = N0.getOperand(0).getValueType();
10408 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10409 unsigned NumConcats = NumElts / NumElemsPerConcat;
10410
10411 // Look at every vector that's inserted. We're looking for exact
10412 // subvector-sized copies from a concatenated vector
10413 for (unsigned I = 0; I != NumConcats; ++I) {
10414 // Make sure we're dealing with a copy.
10415 unsigned Begin = I * NumElemsPerConcat;
Hao Liu3778c042013-05-13 02:07:05 +000010416 bool AllUndef = true, NoUndef = true;
10417 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10418 if (SVN->getMaskElt(J) >= 0)
10419 AllUndef = false;
10420 else
10421 NoUndef = false;
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010422 }
10423
Hao Liu3778c042013-05-13 02:07:05 +000010424 if (NoUndef) {
Hao Liu3778c042013-05-13 02:07:05 +000010425 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10426 return SDValue();
10427
10428 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10429 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10430 return SDValue();
10431
10432 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10433 if (FirstElt < N0.getNumOperands())
10434 Ops.push_back(N0.getOperand(FirstElt));
10435 else
10436 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10437
10438 } else if (AllUndef) {
10439 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10440 } else { // Mixed with general masks and undefs, can't do optimization.
10441 return SDValue();
10442 }
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010443 }
10444
Stephen Hinesdce4a402014-05-29 02:49:00 -070010445 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010446}
10447
Dan Gohman475871a2008-07-27 21:46:04 +000010448SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010449 EVT VT = N->getValueType(0);
Nate Begeman9008ca62009-04-27 18:41:29 +000010450 unsigned NumElts = VT.getVectorNumElements();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010451
Mon P Wangaeb06d22008-11-10 04:46:22 +000010452 SDValue N0 = N->getOperand(0);
Craig Topper481b79c2012-01-04 08:07:43 +000010453 SDValue N1 = N->getOperand(1);
Mon P Wangaeb06d22008-11-10 04:46:22 +000010454
Craig Topperae1bec52012-04-09 05:16:56 +000010455 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wangaeb06d22008-11-10 04:46:22 +000010456
Craig Topper481b79c2012-01-04 08:07:43 +000010457 // Canonicalize shuffle undef, undef -> undef
10458 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10459 return DAG.getUNDEF(VT);
10460
10461 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10462
10463 // Canonicalize shuffle v, v -> v, undef
10464 if (N0 == N1) {
10465 SmallVector<int, 8> NewMask;
10466 for (unsigned i = 0; i != NumElts; ++i) {
10467 int Idx = SVN->getMaskElt(i);
10468 if (Idx >= (int)NumElts) Idx -= NumElts;
10469 NewMask.push_back(Idx);
10470 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010471 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010472 &NewMask[0]);
10473 }
10474
10475 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10476 if (N0.getOpcode() == ISD::UNDEF) {
10477 SmallVector<int, 8> NewMask;
10478 for (unsigned i = 0; i != NumElts; ++i) {
10479 int Idx = SVN->getMaskElt(i);
Craig Topper4b206bd2012-04-09 05:55:33 +000010480 if (Idx >= 0) {
Craig Topper01d22aa2013-08-08 07:38:55 +000010481 if (Idx >= (int)NumElts)
Craig Topper4b206bd2012-04-09 05:55:33 +000010482 Idx -= NumElts;
Craig Topper01d22aa2013-08-08 07:38:55 +000010483 else
10484 Idx = -1; // remove reference to lhs
Craig Topper4b206bd2012-04-09 05:55:33 +000010485 }
10486 NewMask.push_back(Idx);
Craig Topper481b79c2012-01-04 08:07:43 +000010487 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010488 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper481b79c2012-01-04 08:07:43 +000010489 &NewMask[0]);
10490 }
10491
10492 // Remove references to rhs if it is undef
10493 if (N1.getOpcode() == ISD::UNDEF) {
10494 bool Changed = false;
10495 SmallVector<int, 8> NewMask;
10496 for (unsigned i = 0; i != NumElts; ++i) {
10497 int Idx = SVN->getMaskElt(i);
10498 if (Idx >= (int)NumElts) {
10499 Idx = -1;
10500 Changed = true;
10501 }
10502 NewMask.push_back(Idx);
10503 }
10504 if (Changed)
Andrew Trickac6d9be2013-05-25 02:42:55 +000010505 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper481b79c2012-01-04 08:07:43 +000010506 }
Evan Chenge7bec0d2006-07-20 22:44:41 +000010507
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010508 // If it is a splat, check if the argument vector is another splat or a
10509 // build_vector with all scalar elements the same.
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010510 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greifba36cb52008-08-28 21:40:38 +000010511 SDNode *V = N0.getNode();
Evan Cheng917ec982006-07-21 08:25:53 +000010512
Dan Gohman7f321562007-06-25 16:23:39 +000010513 // If this is a bit convert that changes the element type of the vector but
Evan Cheng59569222006-10-16 22:49:37 +000010514 // not the number of vector elements, look through it. Be careful not to
10515 // look though conversions that change things like v4f32 to v2f64.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010516 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman475871a2008-07-27 21:46:04 +000010517 SDValue ConvInput = V->getOperand(0);
Evan Cheng29257862008-07-22 20:42:56 +000010518 if (ConvInput.getValueType().isVector() &&
10519 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greifba36cb52008-08-28 21:40:38 +000010520 V = ConvInput.getNode();
Evan Cheng59569222006-10-16 22:49:37 +000010521 }
10522
Dan Gohman7f321562007-06-25 16:23:39 +000010523 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010524 assert(V->getNumOperands() == NumElts &&
10525 "BUILD_VECTOR has wrong number of operands");
10526 SDValue Base;
10527 bool AllSame = true;
10528 for (unsigned i = 0; i != NumElts; ++i) {
10529 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10530 Base = V->getOperand(i);
10531 break;
Evan Cheng917ec982006-07-21 08:25:53 +000010532 }
Evan Cheng917ec982006-07-21 08:25:53 +000010533 }
Bob Wilson0f1db1a2010-10-28 17:06:14 +000010534 // Splat of <u, u, u, u>, return <u, u, u, u>
10535 if (!Base.getNode())
10536 return N0;
10537 for (unsigned i = 0; i != NumElts; ++i) {
10538 if (V->getOperand(i) != Base) {
10539 AllSame = false;
10540 break;
10541 }
10542 }
10543 // Splat of <x, x, x, x>, return <x, x, x, x>
10544 if (AllSame)
10545 return N0;
Evan Cheng917ec982006-07-21 08:25:53 +000010546 }
10547 }
Nadav Rotem4ac90812012-04-01 19:31:22 +000010548
Benjamin Kramer6fac1fb2013-04-09 17:41:43 +000010549 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10550 Level < AfterLegalizeVectorOps &&
10551 (N1.getOpcode() == ISD::UNDEF ||
10552 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10553 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10554 SDValue V = partitionShuffleOfConcats(N, DAG);
10555
10556 if (V.getNode())
10557 return V;
10558 }
10559
Nadav Rotem4ac90812012-04-01 19:31:22 +000010560 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010561 // and it reverses the swizzle of the previous shuffle then we can
10562 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotem4ac90812012-04-01 19:31:22 +000010563 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10564 N1.getOpcode() == ISD::UNDEF) {
10565
Nadav Rotem4ac90812012-04-01 19:31:22 +000010566 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10567
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010568 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10569 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10570 return SDValue();
10571
Craig Topperae1bec52012-04-09 05:16:56 +000010572 // The incoming shuffle must be of the same type as the result of the
10573 // current shuffle.
10574 assert(OtherSV->getOperand(0).getValueType() == VT &&
10575 "Shuffle types don't match");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010576
10577 for (unsigned i = 0; i != NumElts; ++i) {
10578 int Idx = SVN->getMaskElt(i);
Craig Topperae1bec52012-04-09 05:16:56 +000010579 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotem4ac90812012-04-01 19:31:22 +000010580 // Next, this index comes from the first value, which is the incoming
10581 // shuffle. Adopt the incoming index.
10582 if (Idx >= 0)
10583 Idx = OtherSV->getMaskElt(Idx);
10584
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010585 // The combined shuffle must map each index to itself.
Craig Topperae1bec52012-04-09 05:16:56 +000010586 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010587 return SDValue();
Nadav Rotem4ac90812012-04-01 19:31:22 +000010588 }
Nadav Rotemd16c8d02012-04-07 21:19:08 +000010589
10590 return OtherSV->getOperand(0);
Nadav Rotem4ac90812012-04-01 19:31:22 +000010591 }
10592
Dan Gohman475871a2008-07-27 21:46:04 +000010593 return SDValue();
Chris Lattnerf1d0c622006-03-31 22:16:43 +000010594}
10595
Stephen Hines36b56882014-04-23 16:57:46 -070010596SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10597 SDValue N0 = N->getOperand(0);
10598 SDValue N2 = N->getOperand(2);
10599
10600 // If the input vector is a concatenation, and the insert replaces
10601 // one of the halves, we can optimize into a single concat_vectors.
10602 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10603 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10604 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10605 EVT VT = N->getValueType(0);
10606
10607 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10608 // (concat_vectors Z, Y)
10609 if (InsIdx == 0)
10610 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10611 N->getOperand(1), N0.getOperand(1));
10612
10613 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10614 // (concat_vectors X, Z)
10615 if (InsIdx == VT.getVectorNumElements()/2)
10616 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10617 N0.getOperand(0), N->getOperand(1));
10618 }
10619
10620 return SDValue();
10621}
10622
Evan Cheng44f1f092006-04-20 08:56:16 +000010623/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohman7f321562007-06-25 16:23:39 +000010624/// an AND to a vector_shuffle with the destination vector and a zero vector.
10625/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Cheng44f1f092006-04-20 08:56:16 +000010626/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman475871a2008-07-27 21:46:04 +000010627SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Andersone50ed302009-08-10 22:56:29 +000010628 EVT VT = N->getValueType(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000010629 SDLoc dl(N);
Dan Gohman475871a2008-07-27 21:46:04 +000010630 SDValue LHS = N->getOperand(0);
10631 SDValue RHS = N->getOperand(1);
Dan Gohman7f321562007-06-25 16:23:39 +000010632 if (N->getOpcode() == ISD::AND) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010633 if (RHS.getOpcode() == ISD::BITCAST)
Evan Cheng44f1f092006-04-20 08:56:16 +000010634 RHS = RHS.getOperand(0);
Dan Gohman7f321562007-06-25 16:23:39 +000010635 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman9008ca62009-04-27 18:41:29 +000010636 SmallVector<int, 8> Indices;
10637 unsigned NumElts = RHS.getNumOperands();
Evan Cheng44f1f092006-04-20 08:56:16 +000010638 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010639 SDValue Elt = RHS.getOperand(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010640 if (!isa<ConstantSDNode>(Elt))
Dan Gohman475871a2008-07-27 21:46:04 +000010641 return SDValue();
Craig Topperb7135e52012-04-09 05:59:53 +000010642
10643 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010644 Indices.push_back(i);
Evan Cheng44f1f092006-04-20 08:56:16 +000010645 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman9008ca62009-04-27 18:41:29 +000010646 Indices.push_back(NumElts);
Evan Cheng44f1f092006-04-20 08:56:16 +000010647 else
Dan Gohman475871a2008-07-27 21:46:04 +000010648 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010649 }
10650
10651 // Let's see if the target supports this vector_shuffle.
Owen Andersone50ed302009-08-10 22:56:29 +000010652 EVT RVT = RHS.getValueType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010653 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman475871a2008-07-27 21:46:04 +000010654 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010655
Dan Gohman7f321562007-06-25 16:23:39 +000010656 // Return the new VECTOR_SHUFFLE node.
Dan Gohman8a55ce42009-09-23 21:02:20 +000010657 EVT EltVT = RVT.getVectorElementType();
Nate Begeman9008ca62009-04-27 18:41:29 +000010658 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman8a55ce42009-09-23 21:02:20 +000010659 DAG.getConstant(0, EltVT));
Stephen Hinesdce4a402014-05-29 02:49:00 -070010660 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010661 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman9008ca62009-04-27 18:41:29 +000010662 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010663 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Cheng44f1f092006-04-20 08:56:16 +000010664 }
10665 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010666
Dan Gohman475871a2008-07-27 21:46:04 +000010667 return SDValue();
Evan Cheng44f1f092006-04-20 08:56:16 +000010668}
10669
Dan Gohman7f321562007-06-25 16:23:39 +000010670/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman475871a2008-07-27 21:46:04 +000010671SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilsond7273432010-12-17 23:06:49 +000010672 assert(N->getValueType(0).isVector() &&
10673 "SimplifyVBinOp only works on vectors!");
Dan Gohman7f321562007-06-25 16:23:39 +000010674
Dan Gohman475871a2008-07-27 21:46:04 +000010675 SDValue LHS = N->getOperand(0);
10676 SDValue RHS = N->getOperand(1);
10677 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greifba36cb52008-08-28 21:40:38 +000010678 if (Shuffle.getNode()) return Shuffle;
Evan Cheng44f1f092006-04-20 08:56:16 +000010679
Dan Gohman7f321562007-06-25 16:23:39 +000010680 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattneredab1b92006-04-02 03:25:57 +000010681 // this operation.
Scott Michelfdc40a02009-02-17 22:15:04 +000010682 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohman7f321562007-06-25 16:23:39 +000010683 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Stephen Hines36b56882014-04-23 16:57:46 -070010684 // Check if both vectors are constants. If not bail out.
10685 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10686 cast<BuildVectorSDNode>(RHS)->isConstant()))
10687 return SDValue();
10688
Dan Gohman475871a2008-07-27 21:46:04 +000010689 SmallVector<SDValue, 8> Ops;
Dan Gohman7f321562007-06-25 16:23:39 +000010690 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +000010691 SDValue LHSOp = LHS.getOperand(i);
10692 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling836ca7d2009-01-30 23:59:18 +000010693
Evan Cheng7b336a82006-05-31 06:08:35 +000010694 // Can't fold divide by zero.
Dan Gohman7f321562007-06-25 16:23:39 +000010695 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10696 N->getOpcode() == ISD::FDIV) {
Evan Cheng7b336a82006-05-31 06:08:35 +000010697 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010698 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng7b336a82006-05-31 06:08:35 +000010699 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greifba36cb52008-08-28 21:40:38 +000010700 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng7b336a82006-05-31 06:08:35 +000010701 break;
10702 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010703
Bob Wilsond7273432010-12-17 23:06:49 +000010704 EVT VT = LHSOp.getValueType();
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010705 EVT RVT = RHSOp.getValueType();
10706 if (RVT != VT) {
10707 // Integer BUILD_VECTOR operands may have types larger than the element
10708 // size (e.g., when the element type is not legal). Prior to type
10709 // legalization, the types may not match between the two BUILD_VECTORS.
10710 // Truncate one of the operands to make them match.
10711 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010712 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010713 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010714 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilsondb2b18f2011-10-18 17:34:47 +000010715 VT = RVT;
10716 }
10717 }
Andrew Trickac6d9be2013-05-25 02:42:55 +000010718 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Chenga0839882010-05-18 00:03:40 +000010719 LHSOp, RHSOp);
10720 if (FoldOp.getOpcode() != ISD::UNDEF &&
10721 FoldOp.getOpcode() != ISD::Constant &&
10722 FoldOp.getOpcode() != ISD::ConstantFP)
10723 break;
10724 Ops.push_back(FoldOp);
10725 AddToWorkList(FoldOp.getNode());
Chris Lattneredab1b92006-04-02 03:25:57 +000010726 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010727
Bob Wilsond7273432010-12-17 23:06:49 +000010728 if (Ops.size() == LHS.getNumOperands())
Stephen Hinesdce4a402014-05-29 02:49:00 -070010729 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattneredab1b92006-04-02 03:25:57 +000010730 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010731
Dan Gohman475871a2008-07-27 21:46:04 +000010732 return SDValue();
Chris Lattneredab1b92006-04-02 03:25:57 +000010733}
10734
Craig Topperdd201ff2012-09-11 01:45:21 +000010735/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10736SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topperdd201ff2012-09-11 01:45:21 +000010737 assert(N->getValueType(0).isVector() &&
10738 "SimplifyVUnaryOp only works on vectors!");
10739
10740 SDValue N0 = N->getOperand(0);
10741
10742 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10743 return SDValue();
10744
10745 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10746 SmallVector<SDValue, 8> Ops;
10747 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10748 SDValue Op = N0.getOperand(i);
10749 if (Op.getOpcode() != ISD::UNDEF &&
10750 Op.getOpcode() != ISD::ConstantFP)
10751 break;
10752 EVT EltVT = Op.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +000010753 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topperdd201ff2012-09-11 01:45:21 +000010754 if (FoldOp.getOpcode() != ISD::UNDEF &&
10755 FoldOp.getOpcode() != ISD::ConstantFP)
10756 break;
10757 Ops.push_back(FoldOp);
10758 AddToWorkList(FoldOp.getNode());
10759 }
10760
10761 if (Ops.size() != N0.getNumOperands())
10762 return SDValue();
10763
Stephen Hinesdce4a402014-05-29 02:49:00 -070010764 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topperdd201ff2012-09-11 01:45:21 +000010765}
10766
Andrew Trickac6d9be2013-05-25 02:42:55 +000010767SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000010768 SDValue N1, SDValue N2){
Nate Begemanf845b452005-10-08 00:29:44 +000010769 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelfdc40a02009-02-17 22:15:04 +000010770
Bill Wendling836ca7d2009-01-30 23:59:18 +000010771 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begemanf845b452005-10-08 00:29:44 +000010772 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling836ca7d2009-01-30 23:59:18 +000010773
Nate Begemanf845b452005-10-08 00:29:44 +000010774 // If we got a simplified select_cc node back from SimplifySelectCC, then
10775 // break it down into a new SETCC node, and a new SELECT node, and then return
10776 // the SELECT node, since we were called with a SELECT node.
Gabor Greifba36cb52008-08-28 21:40:38 +000010777 if (SCC.getNode()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010778 // Check to see if we got a select_cc back (to turn into setcc/select).
10779 // Otherwise, just return whatever node we got back, like fabs.
10780 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000010781 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010782 N0.getValueType(),
Scott Michelfdc40a02009-02-17 22:15:04 +000010783 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling836ca7d2009-01-30 23:59:18 +000010784 SCC.getOperand(4));
Gabor Greifba36cb52008-08-28 21:40:38 +000010785 AddToWorkList(SETCC.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010786 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10787 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begemanf845b452005-10-08 00:29:44 +000010788 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000010789
Nate Begemanf845b452005-10-08 00:29:44 +000010790 return SCC;
10791 }
Dan Gohman475871a2008-07-27 21:46:04 +000010792 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000010793}
10794
Chris Lattner40c62d52005-10-18 06:04:22 +000010795/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10796/// are the two values being selected between, see if we can simplify the
Chris Lattner729c6d12006-05-27 00:43:02 +000010797/// select. Callers of this should assume that TheSelect is deleted if this
10798/// returns true. As such, they should return the appropriate thing (e.g. the
10799/// node) back to the top-level of the DAG combiner loop to avoid it being
10800/// looked at.
Scott Michelfdc40a02009-02-17 22:15:04 +000010801bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman475871a2008-07-27 21:46:04 +000010802 SDValue RHS) {
Scott Michelfdc40a02009-02-17 22:15:04 +000010803
Nadav Rotemf94fdb62011-02-11 19:57:47 +000010804 // Cannot simplify select with vector condition
10805 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10806
Chris Lattner40c62d52005-10-18 06:04:22 +000010807 // If this is a select from two identical things, try to pull the operation
10808 // through the select.
Chris Lattner18061612010-09-21 15:46:59 +000010809 if (LHS.getOpcode() != RHS.getOpcode() ||
10810 !LHS.hasOneUse() || !RHS.hasOneUse())
10811 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010812
Chris Lattner18061612010-09-21 15:46:59 +000010813 // If this is a load and the token chain is identical, replace the select
10814 // of two loads with a load through a select of the address to load from.
10815 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10816 // constants have been dropped into the constant pool.
10817 if (LHS.getOpcode() == ISD::LOAD) {
10818 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10819 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010820
Chris Lattner18061612010-09-21 15:46:59 +000010821 // Token chains must be identical.
10822 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sandsd4b9c172008-06-13 19:07:40 +000010823 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner18061612010-09-21 15:46:59 +000010824 LLD->isVolatile() || RLD->isVolatile() ||
10825 // If this is an EXTLOAD, the VT's must match.
10826 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sandsdcfd3a72010-11-18 20:05:18 +000010827 // If this is an EXTLOAD, the kind of extension must match.
10828 (LLD->getExtensionType() != RLD->getExtensionType() &&
10829 // The only exception is if one of the extensions is anyext.
10830 LLD->getExtensionType() != ISD::EXTLOAD &&
10831 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohman75832d72009-10-31 14:14:04 +000010832 // FIXME: this discards src value information. This is
10833 // over-conservative. It would be beneficial to be able to remember
Mon P Wangfe240b12010-01-11 20:12:49 +000010834 // both potential memory locations. Since we are discarding
10835 // src value info, don't do the transformation if the memory
10836 // locations are not in the default address space.
Chris Lattner18061612010-09-21 15:46:59 +000010837 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooperb0fde6d2013-02-12 03:14:50 +000010838 RLD->getPointerInfo().getAddrSpace() != 0 ||
10839 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10840 LLD->getBasePtr().getValueType()))
Chris Lattner18061612010-09-21 15:46:59 +000010841 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010842
Chris Lattnerf1658062010-09-21 15:58:55 +000010843 // Check that the select condition doesn't reach either load. If so,
10844 // folding this will induce a cycle into the DAG. If not, this is safe to
10845 // xform, so create a select of the addresses.
Chris Lattner18061612010-09-21 15:46:59 +000010846 SDValue Addr;
10847 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnerf1658062010-09-21 15:58:55 +000010848 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10849 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10850 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10851 return false;
Nadav Rotem1c5bf3f2012-10-18 18:06:48 +000010852 // The loads must not depend on one another.
10853 if (LLD->isPredecessorOf(RLD) ||
10854 RLD->isPredecessorOf(LLD))
10855 return false;
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010856 Addr = DAG.getSelect(SDLoc(TheSelect),
10857 LLD->getBasePtr().getValueType(),
10858 TheSelect->getOperand(0), LLD->getBasePtr(),
10859 RLD->getBasePtr());
Chris Lattner18061612010-09-21 15:46:59 +000010860 } else { // Otherwise SELECT_CC
Chris Lattnerf1658062010-09-21 15:58:55 +000010861 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10862 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10863
10864 if ((LLD->hasAnyUseOfValue(1) &&
10865 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner77d95212012-03-27 16:27:21 +000010866 (RLD->hasAnyUseOfValue(1) &&
10867 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnerf1658062010-09-21 15:58:55 +000010868 return false;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010869
Andrew Trickac6d9be2013-05-25 02:42:55 +000010870 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnerf1658062010-09-21 15:58:55 +000010871 LLD->getBasePtr().getValueType(),
10872 TheSelect->getOperand(0),
10873 TheSelect->getOperand(1),
10874 LLD->getBasePtr(), RLD->getBasePtr(),
10875 TheSelect->getOperand(4));
Chris Lattner18061612010-09-21 15:46:59 +000010876 }
10877
Chris Lattnerf1658062010-09-21 15:58:55 +000010878 SDValue Load;
10879 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10880 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010881 SDLoc(TheSelect),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010882 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010883 LLD->getChain(), Addr, MachinePointerInfo(),
10884 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooperd752e0f2011-11-08 18:42:53 +000010885 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnerf1658062010-09-21 15:58:55 +000010886 } else {
Duncan Sandsb9064bb2010-11-18 21:16:28 +000010887 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10888 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickac6d9be2013-05-25 02:42:55 +000010889 SDLoc(TheSelect),
Stuart Hastingsa9011292011-02-16 16:23:55 +000010890 TheSelect->getValueType(0),
Richard Sandiford66589dc2013-10-28 11:17:59 +000010891 // FIXME: Discards pointer and TBAA info.
Chris Lattnerf1658062010-09-21 15:58:55 +000010892 LLD->getChain(), Addr, MachinePointerInfo(),
10893 LLD->getMemoryVT(), LLD->isVolatile(),
10894 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner40c62d52005-10-18 06:04:22 +000010895 }
Chris Lattnerf1658062010-09-21 15:58:55 +000010896
10897 // Users of the select now use the result of the load.
10898 CombineTo(TheSelect, Load);
10899
10900 // Users of the old loads now use the new load's chain. We know the
10901 // old-load value is dead now.
10902 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10903 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10904 return true;
Chris Lattner40c62d52005-10-18 06:04:22 +000010905 }
Scott Michelfdc40a02009-02-17 22:15:04 +000010906
Chris Lattner40c62d52005-10-18 06:04:22 +000010907 return false;
10908}
10909
Chris Lattner600fec32009-03-11 05:08:08 +000010910/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10911/// where 'cond' is the comparison specified by CC.
Andrew Trickac6d9be2013-05-25 02:42:55 +000010912SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman475871a2008-07-27 21:46:04 +000010913 SDValue N2, SDValue N3,
10914 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner600fec32009-03-11 05:08:08 +000010915 // (x ? y : y) -> y.
10916 if (N2 == N3) return N2;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010917
Owen Andersone50ed302009-08-10 22:56:29 +000010918 EVT VT = N2.getValueType();
Gabor Greifba36cb52008-08-28 21:40:38 +000010919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10920 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10921 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010922
10923 // Determine if the condition we're dealing with is constant
Matt Arsenault225ed702013-05-18 00:21:46 +000010924 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenff97d4f2009-02-03 00:47:48 +000010925 N0, N1, CC, DL, false);
Gabor Greifba36cb52008-08-28 21:40:38 +000010926 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10927 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000010928
10929 // fold select_cc true, x, y -> x
Dan Gohman002e5d02008-03-13 22:13:53 +000010930 if (SCCC && !SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010931 return N2;
10932 // fold select_cc false, x, y -> y
Dan Gohman002e5d02008-03-13 22:13:53 +000010933 if (SCCC && SCCC->isNullValue())
Nate Begemanf845b452005-10-08 00:29:44 +000010934 return N3;
Scott Michelfdc40a02009-02-17 22:15:04 +000010935
Nate Begemanf845b452005-10-08 00:29:44 +000010936 // Check to see if we can simplify the select into an fabs node
10937 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10938 // Allow either -0.0 or 0.0
Dale Johannesen87503a62007-08-25 22:10:57 +000010939 if (CFP->getValueAPF().isZero()) {
Nate Begemanf845b452005-10-08 00:29:44 +000010940 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10941 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10942 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10943 N2 == N3.getOperand(0))
Bill Wendling836ca7d2009-01-30 23:59:18 +000010944 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000010945
Nate Begemanf845b452005-10-08 00:29:44 +000010946 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10947 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10948 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10949 N2.getOperand(0) == N3)
Bill Wendling836ca7d2009-01-30 23:59:18 +000010950 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begemanf845b452005-10-08 00:29:44 +000010951 }
10952 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010953
Chris Lattner600fec32009-03-11 05:08:08 +000010954 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10955 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10956 // in it. This is a win when the constant is not otherwise available because
10957 // it replaces two constant pool loads with one. We only do this if the FP
10958 // type is known to be legal, because if it isn't, then we are before legalize
10959 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wang0b7a7862009-03-14 00:25:19 +000010960 // messing with soft float) and if the ConstantFP is not legal, because if
10961 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner600fec32009-03-11 05:08:08 +000010962 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10963 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10964 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wang0b7a7862009-03-14 00:25:19 +000010965 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Stephen Hinesdce4a402014-05-29 02:49:00 -070010966 TargetLowering::Legal &&
10967 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10968 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner600fec32009-03-11 05:08:08 +000010969 // If both constants have multiple uses, then we won't need to do an
10970 // extra load, they are likely around in registers for other users.
10971 (TV->hasOneUse() || FV->hasOneUse())) {
10972 Constant *Elts[] = {
10973 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10974 const_cast<ConstantFP*>(TV->getConstantFPValue())
10975 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +000010976 Type *FPTy = Elts[0]->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +000010977 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010978
Chris Lattner600fec32009-03-11 05:08:08 +000010979 // Create a ConstantArray of the two constants.
Jay Foad26701082011-06-22 09:24:39 +000010980 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner600fec32009-03-11 05:08:08 +000010981 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10982 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1606e8e2009-03-13 07:51:59 +000010983 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner600fec32009-03-11 05:08:08 +000010984
10985 // Get the offsets to the 0 and 1 element of the array so that we can
10986 // select between them.
10987 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sands777d2302009-05-09 07:06:46 +000010988 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner600fec32009-03-11 05:08:08 +000010989 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000010990
Chris Lattner600fec32009-03-11 05:08:08 +000010991 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault225ed702013-05-18 00:21:46 +000010992 getSetCCResultType(N0.getValueType()),
Chris Lattner600fec32009-03-11 05:08:08 +000010993 N0, N1, CC);
Dan Gohman7b316c92011-09-22 23:01:29 +000010994 AddToWorkList(Cond.getNode());
Matt Arsenaultb05e4772013-06-14 22:04:37 +000010995 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10996 Cond, One, Zero);
Dan Gohman7b316c92011-09-22 23:01:29 +000010997 AddToWorkList(CstOffset.getNode());
Tom Stellardedd08f72013-08-26 15:06:10 +000010998 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner600fec32009-03-11 05:08:08 +000010999 CstOffset);
Dan Gohman7b316c92011-09-22 23:01:29 +000011000 AddToWorkList(CPIdx.getNode());
Chris Lattner600fec32009-03-11 05:08:08 +000011001 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattner85ca1062010-09-21 07:32:19 +000011002 MachinePointerInfo::getConstantPool(), false,
Pete Cooperd752e0f2011-11-08 18:42:53 +000011003 false, false, Alignment);
Chris Lattner600fec32009-03-11 05:08:08 +000011004
11005 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011006 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011007
Nate Begemanf845b452005-10-08 00:29:44 +000011008 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling836ca7d2009-01-30 23:59:18 +000011009 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnere3152e52006-09-20 06:41:35 +000011010 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohman002e5d02008-03-13 22:13:53 +000011011 (N1C->isNullValue() || // (a < 0) ? b : 0
11012 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Andersone50ed302009-08-10 22:56:29 +000011013 EVT XType = N0.getValueType();
11014 EVT AType = N2.getValueType();
Duncan Sands8e4eb092008-06-08 20:54:56 +000011015 if (XType.bitsGE(AType)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +000011016 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman07ed4172005-10-10 21:26:48 +000011017 // single-bit constant.
Dan Gohman002e5d02008-03-13 22:13:53 +000011018 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11019 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands83ec4b62008-06-06 12:08:01 +000011020 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Anderson95771af2011-02-25 21:41:48 +000011021 SDValue ShCt = DAG.getConstant(ShCtV,
11022 getShiftAmountTy(N0.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011023 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011024 XType, N0, ShCt);
Gabor Greifba36cb52008-08-28 21:40:38 +000011025 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000011026
Duncan Sands8e4eb092008-06-08 20:54:56 +000011027 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000011028 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000011029 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000011030 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011031
11032 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000011033 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011034
Andrew Trickac6d9be2013-05-25 02:42:55 +000011035 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011036 XType, N0,
11037 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011038 getShiftAmountTy(N0.getValueType())));
Gabor Greifba36cb52008-08-28 21:40:38 +000011039 AddToWorkList(Shift.getNode());
Bill Wendling836ca7d2009-01-30 23:59:18 +000011040
Duncan Sands8e4eb092008-06-08 20:54:56 +000011041 if (XType.bitsGT(AType)) {
Bill Wendling9729c5a2009-01-31 03:12:48 +000011042 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greifba36cb52008-08-28 21:40:38 +000011043 AddToWorkList(Shift.getNode());
Nate Begemanf845b452005-10-08 00:29:44 +000011044 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011045
11046 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begemanf845b452005-10-08 00:29:44 +000011047 }
11048 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011049
Owen Andersoned1088a2010-09-22 22:58:22 +000011050 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11051 // where y is has a single bit set.
11052 // A plaintext description would be, we can turn the SELECT_CC into an AND
11053 // when the condition can be materialized as an all-ones register. Any
11054 // single bit-test can be materialized as an all-ones register with
11055 // shift-left and shift-right-arith.
11056 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11057 N0->getValueType(0) == VT &&
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011058 N1C && N1C->isNullValue() &&
Owen Andersoned1088a2010-09-22 22:58:22 +000011059 N2C && N2C->isNullValue()) {
11060 SDValue AndLHS = N0->getOperand(0);
11061 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11062 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11063 // Shift the tested bit over the sign bit.
11064 APInt AndMask = ConstAndRHS->getAPIntValue();
11065 SDValue ShlAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000011066 DAG.getConstant(AndMask.countLeadingZeros(),
11067 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011068 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011069
Owen Andersoned1088a2010-09-22 22:58:22 +000011070 // Now arithmetic right shift it all the way over, so the result is either
11071 // all-ones, or zero.
11072 SDValue ShrAmt =
Owen Anderson95771af2011-02-25 21:41:48 +000011073 DAG.getConstant(AndMask.getBitWidth()-1,
11074 getShiftAmountTy(Shl.getValueType()));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011075 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011076
Owen Andersoned1088a2010-09-22 22:58:22 +000011077 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11078 }
11079 }
11080
Nate Begeman07ed4172005-10-10 21:26:48 +000011081 // fold select C, 16, 0 -> shl C, 4
Dan Gohman002e5d02008-03-13 22:13:53 +000011082 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sands28b77e92011-09-06 19:07:46 +000011083 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11084 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelfdc40a02009-02-17 22:15:04 +000011085
Chris Lattner1eba01e2007-04-11 06:50:51 +000011086 // If the caller doesn't want us to simplify this into a zext of a compare,
11087 // don't do it.
Dan Gohman002e5d02008-03-13 22:13:53 +000011088 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman475871a2008-07-27 21:46:04 +000011089 return SDValue();
Scott Michelfdc40a02009-02-17 22:15:04 +000011090
Nate Begeman07ed4172005-10-10 21:26:48 +000011091 // Get a SetCC of the condition
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011092 // NOTE: Don't create a SETCC if it's not legal on this target.
11093 if (!LegalOperations ||
11094 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault225ed702013-05-18 00:21:46 +000011095 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011096 SDValue Temp, SCC;
11097 // cast from setcc result type to select result type
11098 if (LegalTypes) {
Matt Arsenault225ed702013-05-18 00:21:46 +000011099 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011100 N0, N1, CC);
11101 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +000011102 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011103 N2.getValueType());
11104 else
Andrew Trickac6d9be2013-05-25 02:42:55 +000011105 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011106 N2.getValueType(), SCC);
11107 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011108 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11109 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011110 N2.getValueType(), SCC);
Owen Andersonefcc1ae2012-11-03 00:17:26 +000011111 }
11112
11113 AddToWorkList(SCC.getNode());
11114 AddToWorkList(Temp.getNode());
11115
11116 if (N2C->getAPIntValue() == 1)
11117 return Temp;
11118
11119 // shl setcc result by log2 n2c
Jack Carteradbd3ae2013-10-17 01:34:33 +000011120 return DAG.getNode(
11121 ISD::SHL, DL, N2.getValueType(), Temp,
11122 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11123 getShiftAmountTy(Temp.getValueType())));
Nate Begemanb0d04a72006-02-18 02:40:58 +000011124 }
Nate Begeman07ed4172005-10-10 21:26:48 +000011125 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011126
Nate Begemanf845b452005-10-08 00:29:44 +000011127 // Check to see if this is the equivalent of setcc
11128 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11129 // otherwise, go ahead with the folds.
Dan Gohman002e5d02008-03-13 22:13:53 +000011130 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Andersone50ed302009-08-10 22:56:29 +000011131 EVT XType = N0.getValueType();
Duncan Sands25cf2272008-11-24 14:53:14 +000011132 if (!LegalOperations ||
Matt Arsenault225ed702013-05-18 00:21:46 +000011133 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11134 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begemanf845b452005-10-08 00:29:44 +000011135 if (Res.getValueType() != VT)
Bill Wendling836ca7d2009-01-30 23:59:18 +000011136 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begemanf845b452005-10-08 00:29:44 +000011137 return Res;
11138 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011139
Bill Wendling836ca7d2009-01-30 23:59:18 +000011140 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelfdc40a02009-02-17 22:15:04 +000011141 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sands25cf2272008-11-24 14:53:14 +000011142 (!LegalOperations ||
Duncan Sands184a8762008-06-14 17:48:34 +000011143 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011144 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelfdc40a02009-02-17 22:15:04 +000011145 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands83ec4b62008-06-06 12:08:01 +000011146 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Anderson95771af2011-02-25 21:41:48 +000011147 getShiftAmountTy(Ctlz.getValueType())));
Nate Begemanf845b452005-10-08 00:29:44 +000011148 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011149 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelfdc40a02009-02-17 22:15:04 +000011150 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011151 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling836ca7d2009-01-30 23:59:18 +000011152 XType, DAG.getConstant(0, XType), N0);
Andrew Trickac6d9be2013-05-25 02:42:55 +000011153 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling836ca7d2009-01-30 23:59:18 +000011154 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlingfc4b6772009-02-01 11:19:36 +000011155 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands83ec4b62008-06-06 12:08:01 +000011156 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011157 getShiftAmountTy(XType)));
Nate Begemanf845b452005-10-08 00:29:44 +000011158 }
Bill Wendling836ca7d2009-01-30 23:59:18 +000011159 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begemanf845b452005-10-08 00:29:44 +000011160 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011161 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling836ca7d2009-01-30 23:59:18 +000011162 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011163 getShiftAmountTy(N0.getValueType())));
Bill Wendling836ca7d2009-01-30 23:59:18 +000011164 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begemanf845b452005-10-08 00:29:44 +000011165 }
11166 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011167
Benjamin Kramercde51102010-07-08 12:09:56 +000011168 // Check to see if this is an integer abs.
11169 // select_cc setg[te] X, 0, X, -X ->
11170 // select_cc setgt X, -1, X, -X ->
11171 // select_cc setl[te] X, 0, -X, X ->
11172 // select_cc setlt X, 1, -X, X ->
Nate Begemanf845b452005-10-08 00:29:44 +000011173 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramercde51102010-07-08 12:09:56 +000011174 if (N1C) {
Stephen Hinesdce4a402014-05-29 02:49:00 -070011175 ConstantSDNode *SubC = nullptr;
Benjamin Kramercde51102010-07-08 12:09:56 +000011176 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11177 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11178 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11179 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11180 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11181 (N1C->isOne() && CC == ISD::SETLT)) &&
11182 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11183 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11184
Owen Andersone50ed302009-08-10 22:56:29 +000011185 EVT XType = N0.getValueType();
Benjamin Kramercde51102010-07-08 12:09:56 +000011186 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +000011187 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramercde51102010-07-08 12:09:56 +000011188 N0,
11189 DAG.getConstant(XType.getSizeInBits()-1,
Owen Anderson95771af2011-02-25 21:41:48 +000011190 getShiftAmountTy(N0.getValueType())));
Andrew Trickac6d9be2013-05-25 02:42:55 +000011191 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramercde51102010-07-08 12:09:56 +000011192 XType, N0, Shift);
11193 AddToWorkList(Shift.getNode());
11194 AddToWorkList(Add.getNode());
11195 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begemanf845b452005-10-08 00:29:44 +000011196 }
11197 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011198
Dan Gohman475871a2008-07-27 21:46:04 +000011199 return SDValue();
Nate Begeman44728a72005-09-19 22:34:01 +000011200}
11201
Evan Chengfa1eb272007-02-08 22:13:59 +000011202/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Andersone50ed302009-08-10 22:56:29 +000011203SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman475871a2008-07-27 21:46:04 +000011204 SDValue N1, ISD::CondCode Cond,
Andrew Trickac6d9be2013-05-25 02:42:55 +000011205 SDLoc DL, bool foldBooleans) {
Scott Michelfdc40a02009-02-17 22:15:04 +000011206 TargetLowering::DAGCombinerInfo
Nadav Rotem444b4bf2012-12-27 06:47:41 +000011207 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenff97d4f2009-02-03 00:47:48 +000011208 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman452d7be2005-09-16 00:54:12 +000011209}
11210
Nate Begeman69575232005-10-20 02:15:44 +000011211/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11212/// return a DAG expression to select that will generate the same value by
11213/// multiplying by a magic number. See:
11214/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000011215SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Stephen Hinesdce4a402014-05-29 02:49:00 -070011216 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11217 if (!C)
11218 return SDValue();
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011219
Stephen Hinesdce4a402014-05-29 02:49:00 -070011220 // Avoid division by zero.
11221 if (!C->getAPIntValue())
11222 return SDValue();
11223
11224 std::vector<SDNode*> Built;
11225 SDValue S =
11226 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11227
11228 for (SDNode *N : Built)
11229 AddToWorkList(N);
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011230 return S;
Nate Begeman69575232005-10-20 02:15:44 +000011231}
11232
Stephen Hinesdce4a402014-05-29 02:49:00 -070011233/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begeman69575232005-10-20 02:15:44 +000011234/// return a DAG expression to select that will generate the same value by
11235/// multiplying by a magic number. See:
11236/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman475871a2008-07-27 21:46:04 +000011237SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Stephen Hinesdce4a402014-05-29 02:49:00 -070011238 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11239 if (!C)
11240 return SDValue();
Nate Begeman69575232005-10-20 02:15:44 +000011241
Stephen Hinesdce4a402014-05-29 02:49:00 -070011242 // Avoid division by zero.
11243 if (!C->getAPIntValue())
11244 return SDValue();
11245
11246 std::vector<SDNode*> Built;
11247 SDValue S =
11248 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11249
11250 for (SDNode *N : Built)
11251 AddToWorkList(N);
Andrew Lenharthdae9cbe2006-05-16 17:42:15 +000011252 return S;
Nate Begeman69575232005-10-20 02:15:44 +000011253}
11254
Nate Begemancc66cdd2009-09-25 06:05:26 +000011255/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopher503a64d2010-12-09 04:48:06 +000011256// to alias with anything but itself. Provides base object and offset as
11257// results.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011258static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky2943e372012-09-05 22:15:49 +000011259 const GlobalValue *&GV, const void *&CV) {
Jim Laskey71382342006-10-07 23:37:56 +000011260 // Assume it is a primitive operation.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011261 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelfdc40a02009-02-17 22:15:04 +000011262
Jim Laskey71382342006-10-07 23:37:56 +000011263 // If it's an adding a simple constant then integrate the offset.
11264 if (Base.getOpcode() == ISD::ADD) {
11265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11266 Base = Base.getOperand(0);
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +000011267 Offset += C->getZExtValue();
Jim Laskey71382342006-10-07 23:37:56 +000011268 }
11269 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011270
Nate Begemancc66cdd2009-09-25 06:05:26 +000011271 // Return the underlying GlobalValue, and update the Offset. Return false
11272 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11273 // by multiple nodes with different offsets.
11274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11275 GV = G->getGlobal();
11276 Offset += G->getOffset();
11277 return false;
11278 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011279
Nate Begemancc66cdd2009-09-25 06:05:26 +000011280 // Return the underlying Constant value, and update the Offset. Return false
11281 // for ConstantSDNodes since the same constant pool entry may be represented
11282 // by multiple nodes with different offsets.
11283 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky2943e372012-09-05 22:15:49 +000011284 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11285 : (const void *)C->getConstVal();
Nate Begemancc66cdd2009-09-25 06:05:26 +000011286 Offset += C->getOffset();
11287 return false;
11288 }
Jim Laskey71382342006-10-07 23:37:56 +000011289 // If it's any of the following then it can't alias with anything but itself.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011290 return isa<FrameIndexSDNode>(Base);
Jim Laskey71382342006-10-07 23:37:56 +000011291}
11292
11293/// isAlias - Return true if there is any possibility that the two addresses
11294/// overlap.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011295bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey71382342006-10-07 23:37:56 +000011296 // If they are the same then they must be aliases.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011297 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelfdc40a02009-02-17 22:15:04 +000011298
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011299 // If they are both volatile then they cannot be reordered.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011300 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiforda7be36c2013-10-28 12:00:00 +000011301
Jim Laskey71382342006-10-07 23:37:56 +000011302 // Gather base node and offset information.
Dan Gohman475871a2008-07-27 21:46:04 +000011303 SDValue Base1, Base2;
Jim Laskey71382342006-10-07 23:37:56 +000011304 int64_t Offset1, Offset2;
Dan Gohman46510a72010-04-15 01:51:59 +000011305 const GlobalValue *GV1, *GV2;
Roman Divacky2943e372012-09-05 22:15:49 +000011306 const void *CV1, *CV2;
Stephen Hinesdce4a402014-05-29 02:49:00 -070011307 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11308 Base1, Offset1, GV1, CV1);
11309 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11310 Base2, Offset2, GV2, CV2);
Scott Michelfdc40a02009-02-17 22:15:04 +000011311
Nate Begemancc66cdd2009-09-25 06:05:26 +000011312 // If they have a same base address then check to see if they overlap.
11313 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Stephen Hinesdce4a402014-05-29 02:49:00 -070011314 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11315 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelfdc40a02009-02-17 22:15:04 +000011316
Owen Anderson4a9f1502010-09-20 20:39:59 +000011317 // It is possible for different frame indices to alias each other, mostly
11318 // when tail call optimization reuses return address slots for arguments.
11319 // To catch this case, look up the actual index of frame indices to compute
11320 // the real alias relationship.
11321 if (isFrameIndex1 && isFrameIndex2) {
11322 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11323 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11324 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Stephen Hinesdce4a402014-05-29 02:49:00 -070011325 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11326 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson4a9f1502010-09-20 20:39:59 +000011327 }
11328
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011329 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson4a9f1502010-09-20 20:39:59 +000011330 // we know they cannot alias.
Nate Begemancc66cdd2009-09-25 06:05:26 +000011331 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11332 return false;
Jim Laskey096c22e2006-10-18 12:29:57 +000011333
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011334 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11335 // compared to the size and offset of the access, we may be able to prove they
11336 // do not alias. This check is conservative for now to catch cases created by
11337 // splitting vector types.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011338 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11339 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11340 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11341 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11342 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11343 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11344 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011345
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011346 // There is no overlap between these relatively aligned accesses of similar
11347 // size, return no alias.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011348 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11349 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011350 return false;
11351 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011352
Hal Finkel253acef2013-08-29 03:29:55 +000011353 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11354 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Stephen Hines36b56882014-04-23 16:57:46 -070011355#ifndef NDEBUG
11356 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11357 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11358 UseAA = false;
11359#endif
Stephen Hinesdce4a402014-05-29 02:49:00 -070011360 if (UseAA &&
11361 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey07a27092006-10-18 19:08:31 +000011362 // Use alias analysis information.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011363 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11364 Op1->getSrcValueOffset());
11365 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11366 Op0->getSrcValueOffset() - MinOffset;
11367 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11368 Op1->getSrcValueOffset() - MinOffset;
Scott Michelfdc40a02009-02-17 22:15:04 +000011369 AliasAnalysis::AliasResult AAResult =
Stephen Hinesdce4a402014-05-29 02:49:00 -070011370 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11371 Overlap1,
11372 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11373 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11374 Overlap2,
11375 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey07a27092006-10-18 19:08:31 +000011376 if (AAResult == AliasAnalysis::NoAlias)
11377 return false;
11378 }
Jim Laskey096c22e2006-10-18 12:29:57 +000011379
11380 // Otherwise we have to assume they alias.
11381 return true;
Jim Laskey71382342006-10-07 23:37:56 +000011382}
11383
Jim Laskey6ff23e52006-10-04 16:53:27 +000011384/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11385/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman475871a2008-07-27 21:46:04 +000011386void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Toppera0ec3f92013-07-14 04:42:23 +000011387 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman475871a2008-07-27 21:46:04 +000011388 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011389 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelfdc40a02009-02-17 22:15:04 +000011390
Jim Laskey279f0532006-09-25 16:29:54 +000011391 // Get alias information for node.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011392 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskey279f0532006-09-25 16:29:54 +000011393
Jim Laskey6ff23e52006-10-04 16:53:27 +000011394 // Starting off.
Jim Laskeybc588b82006-10-05 15:07:25 +000011395 Chains.push_back(OriginalChain);
Nate Begeman677c89d2009-10-12 05:53:58 +000011396 unsigned Depth = 0;
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011397
Jim Laskeybc588b82006-10-05 15:07:25 +000011398 // Look at each chain and determine if it is an alias. If so, add it to the
11399 // aliases list. If not, then continue up the chain looking for the next
Scott Michelfdc40a02009-02-17 22:15:04 +000011400 // candidate.
Jim Laskeybc588b82006-10-05 15:07:25 +000011401 while (!Chains.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +000011402 SDValue Chain = Chains.back();
Jim Laskeybc588b82006-10-05 15:07:25 +000011403 Chains.pop_back();
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011404
11405 // For TokenFactor nodes, look at each operand and only continue up the
11406 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begeman677c89d2009-10-12 05:53:58 +000011407 // find more and revert to original chain since the xform is unlikely to be
11408 // profitable.
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011409 //
11410 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begeman677c89d2009-10-12 05:53:58 +000011411 // chain we found before we hit a tokenfactor rather than the original
11412 // chain.
11413 if (Depth > 6 || Aliases.size() == 2) {
11414 Aliases.clear();
11415 Aliases.push_back(OriginalChain);
Stephen Hines36b56882014-04-23 16:57:46 -070011416 return;
Nate Begeman677c89d2009-10-12 05:53:58 +000011417 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011418
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011419 // Don't bother if we've been before.
11420 if (!Visited.insert(Chain.getNode()))
11421 continue;
Scott Michelfdc40a02009-02-17 22:15:04 +000011422
Jim Laskeybc588b82006-10-05 15:07:25 +000011423 switch (Chain.getOpcode()) {
11424 case ISD::EntryToken:
11425 // Entry token is ideal chain operand, but handled in FindBetterChain.
11426 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011427
Jim Laskeybc588b82006-10-05 15:07:25 +000011428 case ISD::LOAD:
11429 case ISD::STORE: {
11430 // Get alias information for Chain.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011431 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11432 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelfdc40a02009-02-17 22:15:04 +000011433
Jim Laskeybc588b82006-10-05 15:07:25 +000011434 // If chain is alias then stop here.
11435 if (!(IsLoad && IsOpLoad) &&
Stephen Hinesdce4a402014-05-29 02:49:00 -070011436 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskeybc588b82006-10-05 15:07:25 +000011437 Aliases.push_back(Chain);
11438 } else {
11439 // Look further up the chain.
Scott Michelfdc40a02009-02-17 22:15:04 +000011440 Chains.push_back(Chain.getOperand(0));
Nate Begeman677c89d2009-10-12 05:53:58 +000011441 ++Depth;
Jim Laskey279f0532006-09-25 16:29:54 +000011442 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011443 break;
11444 }
Scott Michelfdc40a02009-02-17 22:15:04 +000011445
Jim Laskeybc588b82006-10-05 15:07:25 +000011446 case ISD::TokenFactor:
Nate Begemanb6aef5c2009-09-15 00:18:30 +000011447 // We have to check each of the operands of the token factor for "small"
11448 // token factors, so we queue them up. Adding the operands to the queue
11449 // (stack) in reverse order maintains the original order and increases the
11450 // likelihood that getNode will find a matching token factor (CSE.)
11451 if (Chain.getNumOperands() > 16) {
11452 Aliases.push_back(Chain);
11453 break;
11454 }
Jim Laskeybc588b82006-10-05 15:07:25 +000011455 for (unsigned n = Chain.getNumOperands(); n;)
11456 Chains.push_back(Chain.getOperand(--n));
Nate Begeman677c89d2009-10-12 05:53:58 +000011457 ++Depth;
Jim Laskeybc588b82006-10-05 15:07:25 +000011458 break;
Scott Michelfdc40a02009-02-17 22:15:04 +000011459
Jim Laskeybc588b82006-10-05 15:07:25 +000011460 default:
11461 // For all other instructions we will just have to take what we can get.
11462 Aliases.push_back(Chain);
11463 break;
Jim Laskey279f0532006-09-25 16:29:54 +000011464 }
11465 }
Stephen Hines36b56882014-04-23 16:57:46 -070011466
11467 // We need to be careful here to also search for aliases through the
11468 // value operand of a store, etc. Consider the following situation:
11469 // Token1 = ...
11470 // L1 = load Token1, %52
11471 // S1 = store Token1, L1, %51
11472 // L2 = load Token1, %52+8
11473 // S2 = store Token1, L2, %51+8
11474 // Token2 = Token(S1, S2)
11475 // L3 = load Token2, %53
11476 // S3 = store Token2, L3, %52
11477 // L4 = load Token2, %53+8
11478 // S4 = store Token2, L4, %52+8
11479 // If we search for aliases of S3 (which loads address %52), and we look
11480 // only through the chain, then we'll miss the trivial dependence on L1
11481 // (which also loads from %52). We then might change all loads and
11482 // stores to use Token1 as their chain operand, which could result in
11483 // copying %53 into %52 before copying %52 into %51 (which should
11484 // happen first).
11485 //
11486 // The problem is, however, that searching for such data dependencies
11487 // can become expensive, and the cost is not directly related to the
11488 // chain depth. Instead, we'll rule out such configurations here by
11489 // insisting that we've visited all chain users (except for users
11490 // of the original chain, which is not necessary). When doing this,
11491 // we need to look through nodes we don't care about (otherwise, things
11492 // like register copies will interfere with trivial cases).
11493
11494 SmallVector<const SDNode *, 16> Worklist;
11495 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11496 IE = Visited.end(); I != IE; ++I)
11497 if (*I != OriginalChain.getNode())
11498 Worklist.push_back(*I);
11499
11500 while (!Worklist.empty()) {
11501 const SDNode *M = Worklist.pop_back_val();
11502
11503 // We have already visited M, and want to make sure we've visited any uses
11504 // of M that we care about. For uses that we've not visisted, and don't
11505 // care about, queue them to the worklist.
11506
11507 for (SDNode::use_iterator UI = M->use_begin(),
11508 UIE = M->use_end(); UI != UIE; ++UI)
11509 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11510 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11511 // We've not visited this use, and we care about it (it could have an
11512 // ordering dependency with the original node).
11513 Aliases.clear();
11514 Aliases.push_back(OriginalChain);
11515 return;
11516 }
11517
11518 // We've not visited this use, but we don't care about it. Mark it as
11519 // visited and enqueue it to the worklist.
11520 Worklist.push_back(*UI);
11521 }
11522 }
Jim Laskey6ff23e52006-10-04 16:53:27 +000011523}
11524
11525/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11526/// for a better chain (aliasing node.)
Dan Gohman475871a2008-07-27 21:46:04 +000011527SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11528 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelfdc40a02009-02-17 22:15:04 +000011529
Jim Laskey6ff23e52006-10-04 16:53:27 +000011530 // Accumulate all the aliases to this node.
11531 GatherAllAliases(N, OldChain, Aliases);
Scott Michelfdc40a02009-02-17 22:15:04 +000011532
Dan Gohman71dc7c92011-05-17 22:20:36 +000011533 // If no operands then chain to entry token.
11534 if (Aliases.size() == 0)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011535 return DAG.getEntryNode();
Dan Gohman71dc7c92011-05-17 22:20:36 +000011536
11537 // If a single operand then chain to it. We don't need to revisit it.
11538 if (Aliases.size() == 1)
Jim Laskey6ff23e52006-10-04 16:53:27 +000011539 return Aliases[0];
Wesley Peckbf17cfa2010-11-23 03:31:01 +000011540
Jim Laskey6ff23e52006-10-04 16:53:27 +000011541 // Construct a custom tailored token factor.
Stephen Hinesdce4a402014-05-29 02:49:00 -070011542 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskey279f0532006-09-25 16:29:54 +000011543}
11544
Nate Begeman1d4d4142005-09-01 00:19:25 +000011545// SelectionDAG::Combine - This is the entry point for the file.
11546//
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011547void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling98a366d2009-04-29 23:29:43 +000011548 CodeGenOpt::Level OptLevel) {
Nate Begeman1d4d4142005-09-01 00:19:25 +000011549 /// run - This is the main entry point to this class.
11550 ///
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000011551 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman1d4d4142005-09-01 00:19:25 +000011552}