blob: e639d13bd2b535b3b2e4f4b3dab72d2fceac6f9f [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines an instruction selector for the Hexagon target.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "Hexagon.h"
Krzysztof Parzyszeke8926432017-11-10 20:09:46 +000015#include "HexagonISelDAGToDAG.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000016#include "HexagonISelLowering.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000017#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000018#include "HexagonTargetMachine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000019#include "llvm/CodeGen/FunctionLoweringInfo.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000021#include "llvm/CodeGen/SelectionDAGISel.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/IR/Intrinsics.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000023#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000024#include "llvm/Support/Debug.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000025using namespace llvm;
26
Chandler Carruth84e68b22014-04-22 02:41:26 +000027#define DEBUG_TYPE "hexagon-isel"
28
Jyotsna Vermad9225242013-02-13 21:38:46 +000029static
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +000030cl::opt<bool>
31EnableAddressRebalancing("isel-rebalance-addr", cl::Hidden, cl::init(true),
32 cl::desc("Rebalance address calculation trees to improve "
33 "instruction selection"));
34
35// Rebalance only if this allows e.g. combining a GA with an offset or
36// factoring out a shift.
37static
38cl::opt<bool>
39RebalanceOnlyForOptimizations("rebalance-only-opt", cl::Hidden, cl::init(false),
40 cl::desc("Rebalance address tree only if this allows optimizations"));
41
42static
43cl::opt<bool>
44RebalanceOnlyImbalancedTrees("rebalance-only-imbal", cl::Hidden,
45 cl::init(false), cl::desc("Rebalance address tree only if it is imbalanced"));
46
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +000047static cl::opt<bool> CheckSingleUse("hexagon-isel-su", cl::Hidden,
48 cl::init(true), cl::desc("Enable checking of SDNode's single-use status"));
49
Tony Linthicum1213a7a2011-12-12 21:14:40 +000050//===----------------------------------------------------------------------===//
51// Instruction Selector Implementation
52//===----------------------------------------------------------------------===//
53
Krzysztof Parzyszeke8926432017-11-10 20:09:46 +000054#define GET_DAGISEL_BODY HexagonDAGToDAGISel
55#include "HexagonGenDAGISel.inc"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000056
57/// createHexagonISelDag - This pass converts a legalized DAG into a
58/// Hexagon-specific DAG, ready for instruction scheduling.
59///
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000060namespace llvm {
61FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
62 CodeGenOpt::Level OptLevel) {
Jyotsna Vermad9225242013-02-13 21:38:46 +000063 return new HexagonDAGToDAGISel(TM, OptLevel);
Tony Linthicum1213a7a2011-12-12 21:14:40 +000064}
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000065}
Tony Linthicum1213a7a2011-12-12 21:14:40 +000066
Benjamin Kramerbdc49562016-06-12 15:39:02 +000067void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000068 SDValue Chain = LD->getChain();
69 SDValue Base = LD->getBasePtr();
70 SDValue Offset = LD->getOffset();
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000071 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000072 EVT LoadedVT = LD->getMemoryVT();
73 unsigned Opcode = 0;
74
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000075 // Check for zero extended loads. Treat any-extend loads as zero extended
76 // loads.
77 ISD::LoadExtType ExtType = LD->getExtensionType();
78 bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000079 bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +000080
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000081 assert(LoadedVT.isSimple());
82 switch (LoadedVT.getSimpleVT().SimpleTy) {
83 case MVT::i8:
84 if (IsZeroExt)
85 Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000086 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000087 Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
88 break;
89 case MVT::i16:
90 if (IsZeroExt)
91 Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000092 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000093 Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
94 break;
95 case MVT::i32:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +000096 case MVT::v2i16:
97 case MVT::v4i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000098 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
99 break;
100 case MVT::i64:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000101 case MVT::v2i32:
102 case MVT::v4i16:
103 case MVT::v8i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000104 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
105 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000106 case MVT::v64i8:
107 case MVT::v32i16:
108 case MVT::v16i32:
109 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000110 case MVT::v128i8:
111 case MVT::v64i16:
112 case MVT::v32i32:
113 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000114 if (isAlignedMemNode(LD)) {
115 if (LD->isNonTemporal())
116 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
117 else
118 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
119 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000120 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000121 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000122 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000123 default:
124 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000125 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000126
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000127 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
128 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
129 MemOp[0] = LD->getMemOperand();
130
131 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
132 -> MachineSDNode* {
133 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
134 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
135 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
136 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000137 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000138 if (ExtType == ISD::SEXTLOAD)
139 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
140 SDValue(N, 0));
141 return N;
142 };
143
144 // Loaded value Next address Chain
145 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
146 SDValue To[3];
147
148 EVT ValueVT = LD->getValueType(0);
149 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
150 // A load extending to i64 will actually produce i32, which will then
151 // need to be extended to i64.
152 assert(LoadedVT.getSizeInBits() <= 32);
153 ValueVT = MVT::i32;
154 }
155
156 if (IsValidInc) {
157 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
158 MVT::i32, MVT::Other, Base,
159 IncV, Chain);
160 L->setMemRefs(MemOp, MemOp+1);
161 To[1] = SDValue(L, 1); // Next address.
162 To[2] = SDValue(L, 2); // Chain.
163 // Handle special case for extension to i64.
164 if (LD->getValueType(0) == MVT::i64)
165 L = getExt64(L, dl);
166 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000167 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000168 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
169 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
170 Base, Zero, Chain);
171 L->setMemRefs(MemOp, MemOp+1);
172 To[2] = SDValue(L, 1); // Chain.
173 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
174 Base, IncV);
175 To[1] = SDValue(A, 0); // Next address.
176 // Handle special case for extension to i64.
177 if (LD->getValueType(0) == MVT::i64)
178 L = getExt64(L, dl);
179 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000180 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000181 ReplaceUses(From, To, 3);
182 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000183}
184
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000185MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
186 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
187 return nullptr;
188
189 SDLoc dl(IntN);
190 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
191
192 static std::map<unsigned,unsigned> LoadPciMap = {
193 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
194 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
195 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
196 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
197 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
198 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
199 };
200 auto FLC = LoadPciMap.find(IntNo);
201 if (FLC != LoadPciMap.end()) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000202 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
203 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
204 // Operands: { Base, Increment, Modifier, Chain }
205 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
206 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
207 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000208 { IntN->getOperand(2), I, IntN->getOperand(4),
209 IntN->getOperand(0) });
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000210 return Res;
211 }
212
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000213 return nullptr;
214}
215
216SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
217 SDNode *IntN) {
218 // The "LoadN" is just a machine load instruction. The intrinsic also
219 // involves storing it. Generate an appropriate store to the location
220 // given in the intrinsic's operand(3).
221 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
222 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
223 HexagonII::MemAccesSizeMask;
224 unsigned Size = 1U << (SizeBits-1);
225
226 SDLoc dl(IntN);
227 MachinePointerInfo PI;
228 SDValue TS;
229 SDValue Loc = IntN->getOperand(3);
230
231 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000232 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
233 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000234 else
Justin Lebar9c375812016-07-15 18:27:10 +0000235 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
236 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000237
238 SDNode *StoreN;
239 {
240 HandleSDNode Handle(TS);
241 SelectStore(TS.getNode());
242 StoreN = Handle.getValue().getNode();
243 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000244
245 // Load's results are { Loaded value, Updated pointer, Chain }
246 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
247 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
248 return StoreN;
249}
250
Justin Bognerec37a022016-05-12 21:46:18 +0000251bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000252 // The intrinsics for load circ/brev perform two operations:
253 // 1. Load a value V from the specified location, using the addressing
254 // mode corresponding to the intrinsic.
255 // 2. Store V into a specified location. This location is typically a
256 // local, temporary object.
257 // In many cases, the program using these intrinsics will immediately
258 // load V again from the local object. In those cases, when certain
259 // conditions are met, the last load can be removed.
260 // This function identifies and optimizes this pattern. If the pattern
261 // cannot be optimized, it returns nullptr, which will cause the load
262 // to be selected separately from the intrinsic (which will be handled
263 // in SelectIntrinsicWChain).
264
265 SDValue Ch = N->getOperand(0);
266 SDValue Loc = N->getOperand(1);
267
268 // Assume that the load and the intrinsic are connected directly with a
269 // chain:
270 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
271 // t2: i32,ch = load t1:1, Loc, ...
272 SDNode *C = Ch.getNode();
273
274 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000275 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000276
277 // The second load can only be eliminated if its extension type matches
278 // that of the load instruction corresponding to the intrinsic. The user
279 // can provide an address of an unsigned variable to store the result of
280 // a sign-extending intrinsic into (or the other way around).
281 ISD::LoadExtType IntExt;
282 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000283 case Intrinsic::hexagon_circ_ldub:
284 case Intrinsic::hexagon_circ_lduh:
285 IntExt = ISD::ZEXTLOAD;
286 break;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000287 case Intrinsic::hexagon_circ_ldw:
288 case Intrinsic::hexagon_circ_ldd:
289 IntExt = ISD::NON_EXTLOAD;
290 break;
291 default:
292 IntExt = ISD::SEXTLOAD;
293 break;
294 }
295 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000296 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000297
298 // Make sure the target location for the loaded value in the load intrinsic
299 // is the location from which LD (or N) is loading.
300 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000301 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000302
303 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
304 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
305 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
306 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
307 ReplaceUses(F, T, array_lengthof(T));
308 // This transformation will leave the intrinsic dead. If it remains in
309 // the DAG, the selection code will see it again, but without the load,
310 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000311 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000312 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000313 }
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000314 return false;
315}
316
Krzysztof Parzyszekdc7a5572018-03-29 13:52:46 +0000317// Convert the bit-reverse load intrinsic to appropriate target instruction.
318bool HexagonDAGToDAGISel::SelectBrevLdIntrinsic(SDNode *IntN) {
319 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
320 return false;
321
322 const SDLoc &dl(IntN);
323 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
324
325 static const std::map<unsigned, unsigned> LoadBrevMap = {
326 { Intrinsic::hexagon_L2_loadrb_pbr, Hexagon::L2_loadrb_pbr },
327 { Intrinsic::hexagon_L2_loadrub_pbr, Hexagon::L2_loadrub_pbr },
328 { Intrinsic::hexagon_L2_loadrh_pbr, Hexagon::L2_loadrh_pbr },
329 { Intrinsic::hexagon_L2_loadruh_pbr, Hexagon::L2_loadruh_pbr },
330 { Intrinsic::hexagon_L2_loadri_pbr, Hexagon::L2_loadri_pbr },
331 { Intrinsic::hexagon_L2_loadrd_pbr, Hexagon::L2_loadrd_pbr }
332 };
333 auto FLI = LoadBrevMap.find(IntNo);
334 if (FLI != LoadBrevMap.end()) {
335 EVT ValTy =
336 (IntNo == Intrinsic::hexagon_L2_loadrd_pbr) ? MVT::i64 : MVT::i32;
337 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
338 // Operands of Intrinsic: {chain, enum ID of intrinsic, baseptr,
339 // modifier}.
340 // Operands of target instruction: { Base, Modifier, Chain }.
341 MachineSDNode *Res = CurDAG->getMachineNode(
342 FLI->second, dl, RTys,
343 {IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(0)});
344
345 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
346 MemOp[0] = cast<MemIntrinsicSDNode>(IntN)->getMemOperand();
347 Res->setMemRefs(MemOp, MemOp + 1);
348
349 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
350 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
351 ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
352 CurDAG->RemoveDeadNode(IntN);
353 return true;
354 }
355 return false;
356}
357
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000358/// Generate a machine instruction node for the new circlar buffer intrinsics.
359/// The new versions use a CSx register instead of the K field.
360bool HexagonDAGToDAGISel::SelectNewCircIntrinsic(SDNode *IntN) {
361 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
362 return false;
363
364 SDLoc DL(IntN);
365 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
366 SmallVector<SDValue, 7> Ops;
367
368 static std::map<unsigned,unsigned> LoadNPcMap = {
369 { Intrinsic::hexagon_L2_loadrub_pci, Hexagon::PS_loadrub_pci },
370 { Intrinsic::hexagon_L2_loadrb_pci, Hexagon::PS_loadrb_pci },
371 { Intrinsic::hexagon_L2_loadruh_pci, Hexagon::PS_loadruh_pci },
372 { Intrinsic::hexagon_L2_loadrh_pci, Hexagon::PS_loadrh_pci },
373 { Intrinsic::hexagon_L2_loadri_pci, Hexagon::PS_loadri_pci },
374 { Intrinsic::hexagon_L2_loadrd_pci, Hexagon::PS_loadrd_pci },
375 { Intrinsic::hexagon_L2_loadrub_pcr, Hexagon::PS_loadrub_pcr },
376 { Intrinsic::hexagon_L2_loadrb_pcr, Hexagon::PS_loadrb_pcr },
377 { Intrinsic::hexagon_L2_loadruh_pcr, Hexagon::PS_loadruh_pcr },
378 { Intrinsic::hexagon_L2_loadrh_pcr, Hexagon::PS_loadrh_pcr },
379 { Intrinsic::hexagon_L2_loadri_pcr, Hexagon::PS_loadri_pcr },
380 { Intrinsic::hexagon_L2_loadrd_pcr, Hexagon::PS_loadrd_pcr }
381 };
382 auto FLI = LoadNPcMap.find (IntNo);
383 if (FLI != LoadNPcMap.end()) {
384 EVT ValTy = MVT::i32;
385 if (IntNo == Intrinsic::hexagon_L2_loadrd_pci ||
386 IntNo == Intrinsic::hexagon_L2_loadrd_pcr)
387 ValTy = MVT::i64;
388 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
389 // Handle load.*_pci case which has 6 operands.
390 if (IntN->getNumOperands() == 6) {
391 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
392 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
393 // Operands: { Base, Increment, Modifier, Start, Chain }.
394 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
395 IntN->getOperand(0) };
396 } else
397 // Handle load.*_pcr case which has 5 operands.
398 // Operands: { Base, Modifier, Start, Chain }.
399 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
400 IntN->getOperand(0) };
401 MachineSDNode *Res = CurDAG->getMachineNode(FLI->second, DL, RTys, Ops);
402 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
403 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
404 ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
405 CurDAG->RemoveDeadNode(IntN);
406 return true;
407 }
408
409 static std::map<unsigned,unsigned> StoreNPcMap = {
410 { Intrinsic::hexagon_S2_storerb_pci, Hexagon::PS_storerb_pci },
411 { Intrinsic::hexagon_S2_storerh_pci, Hexagon::PS_storerh_pci },
412 { Intrinsic::hexagon_S2_storerf_pci, Hexagon::PS_storerf_pci },
413 { Intrinsic::hexagon_S2_storeri_pci, Hexagon::PS_storeri_pci },
414 { Intrinsic::hexagon_S2_storerd_pci, Hexagon::PS_storerd_pci },
415 { Intrinsic::hexagon_S2_storerb_pcr, Hexagon::PS_storerb_pcr },
416 { Intrinsic::hexagon_S2_storerh_pcr, Hexagon::PS_storerh_pcr },
417 { Intrinsic::hexagon_S2_storerf_pcr, Hexagon::PS_storerf_pcr },
418 { Intrinsic::hexagon_S2_storeri_pcr, Hexagon::PS_storeri_pcr },
419 { Intrinsic::hexagon_S2_storerd_pcr, Hexagon::PS_storerd_pcr }
420 };
421 auto FSI = StoreNPcMap.find (IntNo);
422 if (FSI != StoreNPcMap.end()) {
423 EVT RTys[] = { MVT::i32, MVT::Other };
424 // Handle store.*_pci case which has 7 operands.
425 if (IntN->getNumOperands() == 7) {
426 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
427 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
428 // Operands: { Base, Increment, Modifier, Value, Start, Chain }.
429 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
430 IntN->getOperand(6), IntN->getOperand(0) };
431 } else
432 // Handle store.*_pcr case which has 6 operands.
433 // Operands: { Base, Modifier, Value, Start, Chain }.
434 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
435 IntN->getOperand(5), IntN->getOperand(0) };
436 MachineSDNode *Res = CurDAG->getMachineNode(FSI->second, DL, RTys, Ops);
437 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
438 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
439 CurDAG->RemoveDeadNode(IntN);
440 return true;
441 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000442
Justin Bognerec37a022016-05-12 21:46:18 +0000443 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000444}
445
Justin Bognerec37a022016-05-12 21:46:18 +0000446void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000447 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000448 LoadSDNode *LD = cast<LoadSDNode>(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000449
450 // Handle indexed loads.
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000451 ISD::MemIndexedMode AM = LD->getAddressingMode();
Justin Bognerec37a022016-05-12 21:46:18 +0000452 if (AM != ISD::UNINDEXED) {
453 SelectIndexedLoad(LD, dl);
454 return;
455 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000456
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000457 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000458 if (tryLoadOfLoadIntrinsic(LD))
459 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000460
Justin Bognerec37a022016-05-12 21:46:18 +0000461 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000462}
463
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000464void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000465 SDValue Chain = ST->getChain();
466 SDValue Base = ST->getBasePtr();
467 SDValue Offset = ST->getOffset();
468 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000469 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000470 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000471 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000472 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000473
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000474 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000475 unsigned Opcode = 0;
476
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000477 assert(StoredVT.isSimple());
478 switch (StoredVT.getSimpleVT().SimpleTy) {
479 case MVT::i8:
480 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
481 break;
482 case MVT::i16:
483 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
484 break;
485 case MVT::i32:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000486 case MVT::v2i16:
487 case MVT::v4i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000488 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
489 break;
490 case MVT::i64:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000491 case MVT::v2i32:
492 case MVT::v4i16:
493 case MVT::v8i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000494 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
495 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000496 case MVT::v64i8:
497 case MVT::v32i16:
498 case MVT::v16i32:
499 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000500 case MVT::v128i8:
501 case MVT::v64i16:
502 case MVT::v32i32:
503 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000504 if (isAlignedMemNode(ST)) {
505 if (ST->isNonTemporal())
506 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
507 else
508 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
509 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000510 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000511 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000512 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000513 default:
514 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000515 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000516
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000517 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
518 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000519 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000520 dl, MVT::i32, Value);
521 }
522
523 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000524 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
525 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000526
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000527 // Next address Chain
528 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
529 SDValue To[2];
530
531 if (IsValidInc) {
532 // Build post increment store.
533 SDValue Ops[] = { Base, IncV, Value, Chain };
534 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
535 Ops);
536 S->setMemRefs(MemOp, MemOp + 1);
537 To[0] = SDValue(S, 0);
538 To[1] = SDValue(S, 1);
539 } else {
540 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
541 SDValue Ops[] = { Base, Zero, Value, Chain };
542 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
543 S->setMemRefs(MemOp, MemOp + 1);
544 To[1] = SDValue(S, 0);
545 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
546 Base, IncV);
547 To[0] = SDValue(A, 0);
548 }
549
550 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000551 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000552}
553
Justin Bognerec37a022016-05-12 21:46:18 +0000554void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000555 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000556 StoreSDNode *ST = cast<StoreSDNode>(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000557
558 // Handle indexed stores.
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000559 ISD::MemIndexedMode AM = ST->getAddressingMode();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000560 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000561 SelectIndexedStore(ST, dl);
562 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000563 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000564
Justin Bognerec37a022016-05-12 21:46:18 +0000565 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000566}
567
Justin Bognerec37a022016-05-12 21:46:18 +0000568void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000569 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000570 SDValue Shl_0 = N->getOperand(0);
571 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000572
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000573 auto Default = [this,N] () -> void { SelectCode(N); };
574
575 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
576 return Default();
577
578 // RHS is const.
579 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
580
581 if (Shl_0.getOpcode() == ISD::MUL) {
582 SDValue Mul_0 = Shl_0.getOperand(0); // Val
583 SDValue Mul_1 = Shl_0.getOperand(1); // Const
584 // RHS of mul is const.
585 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
586 int32_t ValConst = C->getSExtValue() << ShlConst;
587 if (isInt<9>(ValConst)) {
588 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
589 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
590 MVT::i32, Mul_0, Val);
591 ReplaceNode(N, Result);
592 return;
593 }
594 }
595 return Default();
596 }
597
598 if (Shl_0.getOpcode() == ISD::SUB) {
599 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
600 SDValue Sub_1 = Shl_0.getOperand(1); // Val
601 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
602 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
603 return Default();
604 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
605 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
606 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
607 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
608 if (isInt<9>(-ValConst)) {
609 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
610 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
611 MVT::i32, Shl2_0, Val);
612 ReplaceNode(N, Result);
613 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000614 }
615 }
616 }
617 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000618
619 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000620}
621
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000622//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000623// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000624//
Justin Bognerec37a022016-05-12 21:46:18 +0000625void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
626 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
627 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000628 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000629 return;
630 }
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000631
Krzysztof Parzyszekdc7a5572018-03-29 13:52:46 +0000632 // Handle bit-reverse load intrinsics.
633 if (SelectBrevLdIntrinsic(N))
634 return;
635
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000636 if (SelectNewCircIntrinsic(N))
637 return;
638
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000639 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
640 if (IntNo == Intrinsic::hexagon_V6_vgathermw ||
641 IntNo == Intrinsic::hexagon_V6_vgathermw_128B ||
642 IntNo == Intrinsic::hexagon_V6_vgathermh ||
643 IntNo == Intrinsic::hexagon_V6_vgathermh_128B ||
644 IntNo == Intrinsic::hexagon_V6_vgathermhw ||
645 IntNo == Intrinsic::hexagon_V6_vgathermhw_128B) {
646 SelectV65Gather(N);
647 return;
648 }
649 if (IntNo == Intrinsic::hexagon_V6_vgathermwq ||
650 IntNo == Intrinsic::hexagon_V6_vgathermwq_128B ||
651 IntNo == Intrinsic::hexagon_V6_vgathermhq ||
652 IntNo == Intrinsic::hexagon_V6_vgathermhq_128B ||
653 IntNo == Intrinsic::hexagon_V6_vgathermhwq ||
654 IntNo == Intrinsic::hexagon_V6_vgathermhwq_128B) {
655 SelectV65GatherPred(N);
656 return;
657 }
658
Justin Bognerec37a022016-05-12 21:46:18 +0000659 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000660}
661
Justin Bognerec37a022016-05-12 21:46:18 +0000662void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000663 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
664 unsigned Bits;
665 switch (IID) {
666 case Intrinsic::hexagon_S2_vsplatrb:
667 Bits = 8;
668 break;
669 case Intrinsic::hexagon_S2_vsplatrh:
670 Bits = 16;
671 break;
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000672 case Intrinsic::hexagon_V6_vaddcarry:
673 case Intrinsic::hexagon_V6_vaddcarry_128B:
674 case Intrinsic::hexagon_V6_vsubcarry:
675 case Intrinsic::hexagon_V6_vsubcarry_128B:
676 SelectHVXDualOutput(N);
677 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000678 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000679 SelectCode(N);
680 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000681 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000682
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000683 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000684 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000685 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000686 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000687 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000688 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000689 SelectCode(R.getNode());
690 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000691 }
Justin Bognerec37a022016-05-12 21:46:18 +0000692 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000693}
694
Sirish Pande69295b82012-05-10 20:20:25 +0000695//
696// Map floating point constant values.
697//
Justin Bognerec37a022016-05-12 21:46:18 +0000698void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000699 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000700 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000701 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000702 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000703 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
704 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000705 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000706 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000707 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000708 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
709 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000710 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000711 }
712
Justin Bognerec37a022016-05-12 21:46:18 +0000713 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000714}
715
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000716//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000717// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000718//
Justin Bognerec37a022016-05-12 21:46:18 +0000719void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000720 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000721 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
722 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
723 ? Hexagon::PS_true
724 : Hexagon::PS_false;
725 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
726 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000727 }
728
Justin Bognerec37a022016-05-12 21:46:18 +0000729 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000730}
731
Justin Bognerec37a022016-05-12 21:46:18 +0000732void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000733 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000734 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000735 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000736 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000737 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000738 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000739 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000740 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000741 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000742
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000743 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000744 // - the object is fixed, or
745 // - there are no objects with higher-than-default alignment, or
746 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000747 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000748 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000749 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000750 } else {
751 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
752 unsigned AR = HMFI.getStackAlignBaseVReg();
753 SDValue CH = CurDAG->getEntryNode();
754 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000755 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000756 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000757
Justin Bognerec37a022016-05-12 21:46:18 +0000758 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000759}
760
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000761void HexagonDAGToDAGISel::SelectVAlign(SDNode *N) {
762 MVT ResTy = N->getValueType(0).getSimpleVT();
763 if (HST->isHVXVectorType(ResTy, true))
764 return SelectHvxVAlign(N);
765
766 const SDLoc &dl(N);
767 unsigned VecLen = ResTy.getSizeInBits();
768 if (VecLen == 32) {
769 SDValue Ops[] = {
770 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
771 N->getOperand(0),
772 CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
773 N->getOperand(1),
774 CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
775 };
776 SDNode *R = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
777 MVT::i64, Ops);
778
779 // Shift right by "(Addr & 0x3) * 8" bytes.
780 SDValue M0 = CurDAG->getTargetConstant(0x18, dl, MVT::i32);
781 SDValue M1 = CurDAG->getTargetConstant(0x03, dl, MVT::i32);
782 SDNode *C = CurDAG->getMachineNode(Hexagon::S4_andi_asl_ri, dl, MVT::i32,
783 M0, N->getOperand(2), M1);
784 SDNode *S = CurDAG->getMachineNode(Hexagon::S2_lsr_r_p, dl, MVT::i64,
785 SDValue(R, 0), SDValue(C, 0));
786 SDValue E = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo, dl, ResTy,
787 SDValue(S, 0));
788 ReplaceNode(N, E.getNode());
789 } else {
790 assert(VecLen == 64);
791 SDNode *Pu = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::v8i1,
792 N->getOperand(2));
793 SDNode *VA = CurDAG->getMachineNode(Hexagon::S2_valignrb, dl, ResTy,
794 N->getOperand(0), N->getOperand(1),
795 SDValue(Pu,0));
796 ReplaceNode(N, VA);
797 }
798}
799
800void HexagonDAGToDAGISel::SelectVAlignAddr(SDNode *N) {
801 const SDLoc &dl(N);
802 SDValue A = N->getOperand(1);
803 int Mask = -cast<ConstantSDNode>(A.getNode())->getSExtValue();
804 assert(isPowerOf2_32(-Mask));
805
806 SDValue M = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
807 SDNode *AA = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
808 N->getOperand(0), M);
809 ReplaceNode(N, AA);
810}
811
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000812// Handle these nodes here to avoid having to write patterns for all
813// combinations of input/output types. In all cases, the resulting
814// instruction is the same.
815void HexagonDAGToDAGISel::SelectTypecast(SDNode *N) {
816 SDValue Op = N->getOperand(0);
817 MVT OpTy = Op.getValueType().getSimpleVT();
818 SDNode *T = CurDAG->MorphNodeTo(N, N->getOpcode(),
819 CurDAG->getVTList(OpTy), {Op});
820 ReplaceNode(T, Op.getNode());
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000821}
822
823void HexagonDAGToDAGISel::SelectP2D(SDNode *N) {
824 MVT ResTy = N->getValueType(0).getSimpleVT();
825 SDNode *T = CurDAG->getMachineNode(Hexagon::C2_mask, SDLoc(N), ResTy,
826 N->getOperand(0));
827 ReplaceNode(N, T);
828}
829
830void HexagonDAGToDAGISel::SelectD2P(SDNode *N) {
831 const SDLoc &dl(N);
832 MVT ResTy = N->getValueType(0).getSimpleVT();
833 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
834 SDNode *T = CurDAG->getMachineNode(Hexagon::A4_vcmpbgtui, dl, ResTy,
835 N->getOperand(0), Zero);
836 ReplaceNode(N, T);
837}
838
839void HexagonDAGToDAGISel::SelectV2Q(SDNode *N) {
840 const SDLoc &dl(N);
841 MVT ResTy = N->getValueType(0).getSimpleVT();
842
843 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
844 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
845 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandvrt, dl, ResTy,
846 N->getOperand(0), SDValue(R,0));
847 ReplaceNode(N, T);
848}
849
850void HexagonDAGToDAGISel::SelectQ2V(SDNode *N) {
851 const SDLoc &dl(N);
852 MVT ResTy = N->getValueType(0).getSimpleVT();
853
854 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
855 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
856 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandqrt, dl, ResTy,
857 N->getOperand(0), SDValue(R,0));
858 ReplaceNode(N, T);
859}
860
Justin Bognerec37a022016-05-12 21:46:18 +0000861void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000862 if (N->isMachineOpcode())
863 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000864
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000865 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000866 case ISD::Constant: return SelectConstant(N);
867 case ISD::ConstantFP: return SelectConstantFP(N);
868 case ISD::FrameIndex: return SelectFrameIndex(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000869 case ISD::SHL: return SelectSHL(N);
870 case ISD::LOAD: return SelectLoad(N);
871 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000872 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
873 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000874 case HexagonISD::VALIGN: return SelectVAlign(N);
875 case HexagonISD::VALIGNADDR: return SelectVAlignAddr(N);
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000876 case HexagonISD::TYPECAST: return SelectTypecast(N);
877 case HexagonISD::P2D: return SelectP2D(N);
878 case HexagonISD::D2P: return SelectD2P(N);
879 case HexagonISD::Q2V: return SelectQ2V(N);
880 case HexagonISD::V2Q: return SelectV2Q(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000881 }
882
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000883 if (HST->useHVXOps()) {
884 switch (N->getOpcode()) {
885 case ISD::VECTOR_SHUFFLE: return SelectHvxShuffle(N);
886 case HexagonISD::VROR: return SelectHvxRor(N);
887 }
888 }
889
Justin Bognerec37a022016-05-12 21:46:18 +0000890 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000891}
892
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000893bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000894SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000895 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000896 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000897
Daniel Sanders60f1db02015-03-13 12:45:09 +0000898 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000899 default:
900 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000901 case InlineAsm::Constraint_i:
902 case InlineAsm::Constraint_o: // Offsetable.
903 case InlineAsm::Constraint_v: // Not offsetable.
904 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000905 if (SelectAddrFI(Inp, Res))
906 OutOps.push_back(Res);
907 else
908 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000909 break;
910 }
911
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000912 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000913 return false;
914}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000915
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000916
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000917static bool isMemOPCandidate(SDNode *I, SDNode *U) {
918 // I is an operand of U. Check if U is an arithmetic (binary) operation
919 // usable in a memop, where the other operand is a loaded value, and the
920 // result of U is stored in the same location.
921
922 if (!U->hasOneUse())
923 return false;
924 unsigned Opc = U->getOpcode();
925 switch (Opc) {
926 case ISD::ADD:
927 case ISD::SUB:
928 case ISD::AND:
929 case ISD::OR:
930 break;
931 default:
932 return false;
933 }
934
935 SDValue S0 = U->getOperand(0);
936 SDValue S1 = U->getOperand(1);
937 SDValue SY = (S0.getNode() == I) ? S1 : S0;
938
939 SDNode *UUse = *U->use_begin();
940 if (UUse->getNumValues() != 1)
941 return false;
942
943 // Check if one of the inputs to U is a load instruction and the output
944 // is used by a store instruction. If so and they also have the same
945 // base pointer, then don't preoprocess this node sequence as it
946 // can be matched to a memop.
947 SDNode *SYNode = SY.getNode();
948 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
949 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
950 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
951 if (LDBasePtr == STBasePtr)
952 return true;
953 }
954 return false;
955}
956
957
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000958// Transform: (or (select c x 0) z) -> (select c (or x z) z)
959// (or (select c 0 y) z) -> (select c z (or y z))
960void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000961 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000962
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000963 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000964 if (I->getOpcode() != ISD::OR)
965 continue;
966
967 auto IsZero = [] (const SDValue &V) -> bool {
968 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
969 return SC->isNullValue();
970 return false;
971 };
972 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
973 if (Op.getOpcode() != ISD::SELECT)
974 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000975 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000976 };
977
978 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
979 EVT VT = I->getValueType(0);
980 bool SelN0 = IsSelect0(N0);
981 SDValue SOp = SelN0 ? N0 : N1;
982 SDValue VOp = SelN0 ? N1 : N0;
983
984 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
985 SDValue SC = SOp.getOperand(0);
986 SDValue SX = SOp.getOperand(1);
987 SDValue SY = SOp.getOperand(2);
988 SDLoc DLS = SOp;
989 if (IsZero(SY)) {
990 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
991 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
992 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
993 } else if (IsZero(SX)) {
994 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
995 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
996 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
997 }
998 }
999 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001000}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001001
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001002// Transform: (store ch val (add x (add (shl y c) e)))
1003// to: (store ch val (add x (shl (add y d) c))),
1004// where e = (shl d c) for some integer d.
1005// The purpose of this is to enable generation of loads/stores with
1006// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1007// value c must be 0, 1 or 2.
1008void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
1009 SelectionDAG &DAG = *CurDAG;
1010
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001011 for (auto I : Nodes) {
1012 if (I->getOpcode() != ISD::STORE)
1013 continue;
1014
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001015 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001016 SDValue Off = I->getOperand(2);
1017 // Off needs to match: (add x (add (shl y c) (shl d c))))
1018 if (Off.getOpcode() != ISD::ADD)
1019 continue;
1020 // Off matched: (add x T0)
1021 SDValue T0 = Off.getOperand(1);
1022 // T0 needs to match: (add T1 T2):
1023 if (T0.getOpcode() != ISD::ADD)
1024 continue;
1025 // T0 matched: (add T1 T2)
1026 SDValue T1 = T0.getOperand(0);
1027 SDValue T2 = T0.getOperand(1);
1028 // T1 needs to match: (shl y c)
1029 if (T1.getOpcode() != ISD::SHL)
1030 continue;
1031 SDValue C = T1.getOperand(1);
1032 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1033 if (CN == nullptr)
1034 continue;
1035 unsigned CV = CN->getZExtValue();
1036 if (CV > 2)
1037 continue;
1038 // T2 needs to match e, where e = (shl d c) for some d.
1039 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1040 if (EN == nullptr)
1041 continue;
1042 unsigned EV = EN->getZExtValue();
1043 if (EV % (1 << CV) != 0)
1044 continue;
1045 unsigned DV = EV / (1 << CV);
1046
1047 // Replace T0 with: (shl (add y d) c)
1048 SDLoc DL = SDLoc(I);
1049 EVT VT = T0.getValueType();
1050 SDValue D = DAG.getConstant(DV, DL, VT);
1051 // NewAdd = (add y d)
1052 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1053 // NewShl = (shl NewAdd c)
1054 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1055 ReplaceNode(T0.getNode(), NewShl.getNode());
1056 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001057}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001058
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001059// Transform: (load ch (add x (and (srl y c) Mask)))
1060// to: (load ch (add x (shl (srl y d) d-c)))
1061// where
1062// Mask = 00..0 111..1 0.0
1063// | | +-- d-c 0s, and d-c is 0, 1 or 2.
1064// | +-------- 1s
1065// +-------------- at most c 0s
1066// Motivating example:
1067// DAG combiner optimizes (add x (shl (srl y 5) 2))
1068// to (add x (and (srl y 3) 1FFFFFFC))
1069// which results in a constant-extended and(##...,lsr). This transformation
1070// undoes this simplification for cases where the shl can be folded into
1071// an addressing mode.
1072void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1073 SelectionDAG &DAG = *CurDAG;
1074
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001075 for (SDNode *N : Nodes) {
1076 unsigned Opc = N->getOpcode();
1077 if (Opc != ISD::LOAD && Opc != ISD::STORE)
1078 continue;
1079 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
1080 // Addr must match: (add x T0)
1081 if (Addr.getOpcode() != ISD::ADD)
1082 continue;
1083 SDValue T0 = Addr.getOperand(1);
1084 // T0 must match: (and T1 Mask)
1085 if (T0.getOpcode() != ISD::AND)
1086 continue;
1087
1088 // We have an AND.
1089 //
1090 // Check the first operand. It must be: (srl y c).
1091 SDValue S = T0.getOperand(0);
1092 if (S.getOpcode() != ISD::SRL)
1093 continue;
1094 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
1095 if (SN == nullptr)
1096 continue;
1097 if (SN->getAPIntValue().getBitWidth() != 32)
1098 continue;
1099 uint32_t CV = SN->getZExtValue();
1100
1101 // Check the second operand: the supposed mask.
1102 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
1103 if (MN == nullptr)
1104 continue;
1105 if (MN->getAPIntValue().getBitWidth() != 32)
1106 continue;
1107 uint32_t Mask = MN->getZExtValue();
1108 // Examine the mask.
1109 uint32_t TZ = countTrailingZeros(Mask);
1110 uint32_t M1 = countTrailingOnes(Mask >> TZ);
1111 uint32_t LZ = countLeadingZeros(Mask);
1112 // Trailing zeros + middle ones + leading zeros must equal the width.
1113 if (TZ + M1 + LZ != 32)
1114 continue;
1115 // The number of trailing zeros will be encoded in the addressing mode.
1116 if (TZ > 2)
1117 continue;
1118 // The number of leading zeros must be at most c.
1119 if (LZ > CV)
1120 continue;
1121
1122 // All looks good.
1123 SDValue Y = S.getOperand(0);
1124 EVT VT = Addr.getValueType();
1125 SDLoc dl(S);
1126 // TZ = D-C, so D = TZ+C.
1127 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1128 SDValue DC = DAG.getConstant(TZ, dl, VT);
1129 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1130 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1131 ReplaceNode(T0.getNode(), NewShl.getNode());
1132 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001133}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001134
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001135// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1136// (op ... 1 ...))
1137void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1138 SelectionDAG &DAG = *CurDAG;
1139
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001140 for (SDNode *N : Nodes) {
1141 unsigned Opc = N->getOpcode();
1142 if (Opc != ISD::ZERO_EXTEND)
1143 continue;
1144 SDValue OpI1 = N->getOperand(0);
1145 EVT OpVT = OpI1.getValueType();
1146 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1147 continue;
1148 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1149 SDNode *U = *I;
1150 if (U->getNumValues() != 1)
1151 continue;
1152 EVT UVT = U->getValueType(0);
1153 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1154 continue;
1155 if (isMemOPCandidate(N, U))
1156 continue;
1157
1158 // Potentially simplifiable operation.
1159 unsigned I1N = I.getOperandNo();
1160 SmallVector<SDValue,2> Ops(U->getNumOperands());
1161 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1162 Ops[i] = U->getOperand(i);
1163 EVT BVT = Ops[I1N].getValueType();
1164
1165 SDLoc dl(U);
1166 SDValue C0 = DAG.getConstant(0, dl, BVT);
1167 SDValue C1 = DAG.getConstant(1, dl, BVT);
1168 SDValue If0, If1;
1169
1170 if (isa<MachineSDNode>(U)) {
1171 unsigned UseOpc = U->getMachineOpcode();
1172 Ops[I1N] = C0;
1173 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1174 Ops[I1N] = C1;
1175 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1176 } else {
1177 unsigned UseOpc = U->getOpcode();
1178 Ops[I1N] = C0;
1179 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1180 Ops[I1N] = C1;
1181 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1182 }
1183 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1184 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1185 }
1186 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001187}
1188
1189void HexagonDAGToDAGISel::PreprocessISelDAG() {
1190 // Repack all nodes before calling each preprocessing function,
1191 // because each of them can modify the set of nodes.
1192 auto getNodes = [this] () -> std::vector<SDNode*> {
1193 std::vector<SDNode*> T;
1194 T.reserve(CurDAG->allnodes_size());
1195 for (SDNode &N : CurDAG->allnodes())
1196 T.push_back(&N);
1197 return T;
1198 };
1199
1200 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1201 // (or (select c 0 y) z) -> (select c z (or y z))
1202 ppSimplifyOrSelect0(getNodes());
1203
1204 // Transform: (store ch val (add x (add (shl y c) e)))
1205 // to: (store ch val (add x (shl (add y d) c))),
1206 // where e = (shl d c) for some integer d.
1207 // The purpose of this is to enable generation of loads/stores with
1208 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1209 // value c must be 0, 1 or 2.
1210 ppAddrReorderAddShl(getNodes());
1211
1212 // Transform: (load ch (add x (and (srl y c) Mask)))
1213 // to: (load ch (add x (shl (srl y d) d-c)))
1214 // where
1215 // Mask = 00..0 111..1 0.0
1216 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1217 // | +-------- 1s
1218 // +-------------- at most c 0s
1219 // Motivating example:
1220 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1221 // to (add x (and (srl y 3) 1FFFFFFC))
1222 // which results in a constant-extended and(##...,lsr). This transformation
1223 // undoes this simplification for cases where the shl can be folded into
1224 // an addressing mode.
1225 ppAddrRewriteAndSrl(getNodes());
1226
1227 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1228 // (op ... 1 ...))
1229 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001230
1231 DEBUG_WITH_TYPE("isel", {
1232 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1233 CurDAG->dump();
1234 });
1235
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001236 if (EnableAddressRebalancing) {
1237 rebalanceAddressTrees();
1238
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001239 DEBUG_WITH_TYPE("isel", {
1240 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001241 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001242 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001243 }
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001244}
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001245
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001246void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1247 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1248 auto &HFI = *HST.getFrameLowering();
1249 if (!HFI.needsAligna(*MF))
1250 return;
1251
1252 MachineFrameInfo &MFI = MF->getFrameInfo();
1253 MachineBasicBlock *EntryBB = &MF->front();
1254 unsigned AR = FuncInfo->CreateReg(MVT::i32);
1255 unsigned MaxA = MFI.getMaxAlignment();
1256 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
1257 .addImm(MaxA);
1258 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001259}
1260
1261// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001262bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001263 if (N.getOpcode() != ISD::FrameIndex)
1264 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001266 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001267 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001268 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001269 return false;
1270 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001271 return true;
1272}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001273
Colin LeMahieu987b0942015-02-04 20:38:01 +00001274inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001275 return SelectGlobalAddress(N, R, false, 0);
Colin LeMahieu987b0942015-02-04 20:38:01 +00001276}
1277
Colin LeMahieu51491352015-02-04 22:36:28 +00001278inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001279 return SelectGlobalAddress(N, R, true, 0);
1280}
1281
1282inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1283 return SelectAnyImmediate(N, R, 0);
1284}
1285
1286inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1287 return SelectAnyImmediate(N, R, 0);
1288}
1289inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1290 return SelectAnyImmediate(N, R, 1);
1291}
1292inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1293 return SelectAnyImmediate(N, R, 2);
1294}
1295inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1296 return SelectAnyImmediate(N, R, 3);
1297}
1298
1299inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1300 EVT T = N.getValueType();
1301 if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1302 return false;
1303 R = N;
1304 return true;
1305}
1306
1307bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1308 uint32_t LogAlign) {
1309 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001310 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001311 };
1312
1313 switch (N.getOpcode()) {
1314 case ISD::Constant: {
1315 if (N.getValueType() != MVT::i32)
1316 return false;
1317 int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1318 if (!IsAligned(V))
1319 return false;
1320 R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1321 return true;
1322 }
1323 case HexagonISD::JT:
1324 case HexagonISD::CP:
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001325 // These are assumed to always be aligned at least 8-byte boundary.
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001326 if (LogAlign > 3)
1327 return false;
1328 R = N.getOperand(0);
1329 return true;
1330 case ISD::ExternalSymbol:
1331 // Symbols may be aligned at any boundary.
1332 if (LogAlign > 0)
1333 return false;
1334 R = N;
1335 return true;
1336 case ISD::BlockAddress:
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001337 // Block address is always aligned at least 4-byte boundary.
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001338 if (LogAlign > 2 || !IsAligned(cast<BlockAddressSDNode>(N)->getOffset()))
1339 return false;
1340 R = N;
1341 return true;
1342 }
1343
1344 if (SelectGlobalAddress(N, R, false, LogAlign) ||
1345 SelectGlobalAddress(N, R, true, LogAlign))
1346 return true;
1347
1348 return false;
Colin LeMahieu51491352015-02-04 22:36:28 +00001349}
1350
Colin LeMahieu987b0942015-02-04 20:38:01 +00001351bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001352 bool UseGP, uint32_t LogAlign) {
1353 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001354 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001355 };
1356
Colin LeMahieu987b0942015-02-04 20:38:01 +00001357 switch (N.getOpcode()) {
1358 case ISD::ADD: {
1359 SDValue N0 = N.getOperand(0);
1360 SDValue N1 = N.getOperand(1);
1361 unsigned GAOpc = N0.getOpcode();
1362 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1363 return false;
1364 if (!UseGP && GAOpc != HexagonISD::CONST32)
1365 return false;
1366 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1367 SDValue Addr = N0.getOperand(0);
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001368 // For the purpose of alignment, sextvalue and zextvalue are the same.
1369 if (!IsAligned(Const->getZExtValue()))
1370 return false;
Colin LeMahieu987b0942015-02-04 20:38:01 +00001371 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1372 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1373 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1374 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1375 N.getValueType(), NewOff);
1376 return true;
1377 }
1378 }
1379 }
1380 break;
1381 }
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001382 case HexagonISD::CP:
1383 case HexagonISD::JT:
Colin LeMahieu987b0942015-02-04 20:38:01 +00001384 case HexagonISD::CONST32:
1385 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1386 // want in the instruction.
1387 if (!UseGP)
1388 R = N.getOperand(0);
1389 return !UseGP;
1390 case HexagonISD::CONST32_GP:
1391 if (UseGP)
1392 R = N.getOperand(0);
1393 return UseGP;
1394 default:
1395 return false;
1396 }
1397
1398 return false;
1399}
1400
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001401bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1402 // This (complex pattern) function is meant to detect a sign-extension
1403 // i32->i64 on a per-operand basis. This would allow writing single
1404 // patterns that would cover a number of combinations of different ways
1405 // a sign-extensions could be written. For example:
1406 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1407 // could match either one of these:
1408 // (mul (sext x) (sext_inreg y))
1409 // (mul (sext-load *p) (sext_inreg y))
1410 // (mul (sext_inreg x) (sext y))
1411 // etc.
1412 //
1413 // The returned value will have type i64 and its low word will
1414 // contain the value being extended. The high bits are not specified.
1415 // The returned type is i64 because the original type of N was i64,
1416 // but the users of this function should only use the low-word of the
1417 // result, e.g.
1418 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1419
1420 if (N.getValueType() != MVT::i64)
1421 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001422 unsigned Opc = N.getOpcode();
1423 switch (Opc) {
1424 case ISD::SIGN_EXTEND:
1425 case ISD::SIGN_EXTEND_INREG: {
1426 // sext_inreg has the source type as a separate operand.
1427 EVT T = Opc == ISD::SIGN_EXTEND
1428 ? N.getOperand(0).getValueType()
1429 : cast<VTSDNode>(N.getOperand(1))->getVT();
Krzysztof Parzyszek2373f8f2018-02-27 22:44:41 +00001430 unsigned SW = T.getSizeInBits();
1431 if (SW == 32)
1432 R = N.getOperand(0);
1433 else if (SW < 32)
1434 R = N;
1435 else
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001436 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001437 break;
1438 }
1439 case ISD::LOAD: {
1440 LoadSDNode *L = cast<LoadSDNode>(N);
1441 if (L->getExtensionType() != ISD::SEXTLOAD)
1442 return false;
1443 // All extending loads extend to i32, so even if the value in
1444 // memory is shorter than 32 bits, it will be i32 after the load.
1445 if (L->getMemoryVT().getSizeInBits() > 32)
1446 return false;
1447 R = N;
1448 break;
1449 }
Krzysztof Parzyszek2373f8f2018-02-27 22:44:41 +00001450 case ISD::SRA: {
1451 auto *S = dyn_cast<ConstantSDNode>(N.getOperand(1));
1452 if (!S || S->getZExtValue() != 32)
1453 return false;
1454 R = N;
1455 break;
1456 }
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001457 default:
1458 return false;
1459 }
1460 EVT RT = R.getValueType();
1461 if (RT == MVT::i64)
1462 return true;
1463 assert(RT == MVT::i32);
1464 // This is only to produce a value of type i64. Do not rely on the
1465 // high bits produced by this.
1466 const SDLoc &dl(N);
1467 SDValue Ops[] = {
1468 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1469 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1470 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1471 };
1472 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1473 MVT::i64, Ops);
1474 R = SDValue(T, 0);
1475 return true;
1476}
1477
1478bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1479 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001480 unsigned Opc = Val.getOpcode();
1481 switch (Opc) {
1482 case ISD::SIGN_EXTEND:
1483 case ISD::ZERO_EXTEND:
1484 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001485 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001486 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001487 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001488 Src = Op0;
1489 return true;
1490 }
1491 break;
1492 }
1493 case ISD::SIGN_EXTEND_INREG:
1494 case ISD::AssertSext:
1495 case ISD::AssertZext:
1496 if (Val.getOperand(0).getValueType().isInteger()) {
1497 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001498 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001499 Src = Val.getOperand(0);
1500 return true;
1501 }
1502 }
1503 break;
1504 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001505 // Check if this is an AND with NumBits of lower bits set to 1.
1506 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001507 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001508 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001509 Src = Val.getOperand(1);
1510 return true;
1511 }
1512 }
1513 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001514 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001515 Src = Val.getOperand(0);
1516 return true;
1517 }
1518 }
1519 break;
1520 }
1521 case ISD::OR:
1522 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001523 // OR/XOR with the lower NumBits bits set to 0.
1524 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001526 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001527 Src = Val.getOperand(1);
1528 return true;
1529 }
1530 }
1531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001532 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001533 Src = Val.getOperand(0);
1534 return true;
1535 }
1536 }
1537 }
1538 default:
1539 break;
1540 }
1541 return false;
1542}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001543
1544bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1545 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1546}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001547
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001548bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1549 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1550 switch (N->getMemoryVT().getStoreSize()) {
1551 case 1:
1552 return StackSize <= 56; // 1*2^6 - 8
1553 case 2:
1554 return StackSize <= 120; // 2*2^6 - 8
1555 case 4:
1556 return StackSize <= 248; // 4*2^6 - 8
1557 default:
1558 return false;
1559 }
1560}
1561
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001562// Return true when the given node fits in a positive half word.
1563bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1564 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1565 int64_t V = CN->getSExtValue();
1566 return V > 0 && isInt<16>(V);
1567 }
1568 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1569 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1570 return VN->getVT().getSizeInBits() <= 16;
1571 }
1572 return false;
1573}
1574
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001575bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1576 return !CheckSingleUse || N->hasOneUse();
1577}
1578
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001579////////////////////////////////////////////////////////////////////////////////
1580// Rebalancing of address calculation trees
1581
1582static bool isOpcodeHandled(const SDNode *N) {
1583 switch (N->getOpcode()) {
1584 case ISD::ADD:
1585 case ISD::MUL:
1586 return true;
1587 case ISD::SHL:
1588 // We only handle constant shifts because these can be easily flattened
1589 // into multiplications by 2^Op1.
1590 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1591 default:
1592 return false;
1593 }
1594}
1595
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001596/// Return the weight of an SDNode
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001597int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1598 if (!isOpcodeHandled(N))
1599 return 1;
1600 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1601 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1602 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1603 return RootWeights[N];
1604}
1605
1606int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1607 if (!isOpcodeHandled(N))
1608 return 0;
1609 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1610 "Cannot query height of unvisited/RAUW'd node!");
1611 return RootHeights[N];
1612}
1613
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001614namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001615struct WeightedLeaf {
1616 SDValue Value;
1617 int Weight;
1618 int InsertionOrder;
1619
1620 WeightedLeaf() : Value(SDValue()) { }
1621
1622 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1623 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1624 assert(Weight >= 0 && "Weight must be >= 0");
1625 }
1626
1627 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1628 assert(A.Value.getNode() && B.Value.getNode());
1629 return A.Weight == B.Weight ?
1630 (A.InsertionOrder > B.InsertionOrder) :
1631 (A.Weight > B.Weight);
1632 }
1633};
1634
1635/// A specialized priority queue for WeigthedLeaves. It automatically folds
1636/// constants and allows removal of non-top elements while maintaining the
1637/// priority order.
1638class LeafPrioQueue {
1639 SmallVector<WeightedLeaf, 8> Q;
1640 bool HaveConst;
1641 WeightedLeaf ConstElt;
1642 unsigned Opcode;
1643
1644public:
1645 bool empty() {
1646 return (!HaveConst && Q.empty());
1647 }
1648
1649 size_t size() {
1650 return Q.size() + HaveConst;
1651 }
1652
1653 bool hasConst() {
1654 return HaveConst;
1655 }
1656
1657 const WeightedLeaf &top() {
1658 if (HaveConst)
1659 return ConstElt;
1660 return Q.front();
1661 }
1662
1663 WeightedLeaf pop() {
1664 if (HaveConst) {
1665 HaveConst = false;
1666 return ConstElt;
1667 }
1668 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1669 return Q.pop_back_val();
1670 }
1671
1672 void push(WeightedLeaf L, bool SeparateConst=true) {
1673 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1674 if (Opcode == ISD::MUL &&
1675 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1676 return;
1677 if (Opcode == ISD::ADD &&
1678 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1679 return;
1680
1681 HaveConst = true;
1682 ConstElt = L;
1683 } else {
1684 Q.push_back(L);
1685 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1686 }
1687 }
1688
1689 /// Push L to the bottom of the queue regardless of its weight. If L is
1690 /// constant, it will not be folded with other constants in the queue.
1691 void pushToBottom(WeightedLeaf L) {
1692 L.Weight = 1000;
1693 push(L, false);
1694 }
1695
1696 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1697 /// lowest weight and remove it from the queue.
1698 WeightedLeaf findSHL(uint64_t MaxAmount);
1699
1700 WeightedLeaf findMULbyConst();
1701
1702 LeafPrioQueue(unsigned Opcode) :
1703 HaveConst(false), Opcode(Opcode) { }
1704};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001705} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001706
1707WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1708 int ResultPos;
1709 WeightedLeaf Result;
1710
1711 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1712 const WeightedLeaf &L = Q[Pos];
1713 const SDValue &Val = L.Value;
1714 if (Val.getOpcode() != ISD::SHL ||
1715 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1716 Val.getConstantOperandVal(1) > MaxAmount)
1717 continue;
1718 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1719 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1720 {
1721 Result = L;
1722 ResultPos = Pos;
1723 }
1724 }
1725
1726 if (Result.Value.getNode()) {
1727 Q.erase(&Q[ResultPos]);
1728 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1729 }
1730
1731 return Result;
1732}
1733
1734WeightedLeaf LeafPrioQueue::findMULbyConst() {
1735 int ResultPos;
1736 WeightedLeaf Result;
1737
1738 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1739 const WeightedLeaf &L = Q[Pos];
1740 const SDValue &Val = L.Value;
1741 if (Val.getOpcode() != ISD::MUL ||
1742 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1743 Val.getConstantOperandVal(1) > 127)
1744 continue;
1745 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1746 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1747 {
1748 Result = L;
1749 ResultPos = Pos;
1750 }
1751 }
1752
1753 if (Result.Value.getNode()) {
1754 Q.erase(&Q[ResultPos]);
1755 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1756 }
1757
1758 return Result;
1759}
1760
1761SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001762 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001763 return CurDAG->getConstant(MulFactor, SDLoc(N),
1764 N->getOperand(1).getValueType());
1765}
1766
1767/// @returns the value x for which 2^x is a factor of Val
1768static unsigned getPowerOf2Factor(SDValue Val) {
1769 if (Val.getOpcode() == ISD::MUL) {
1770 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001771 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1773 if (!C)
1774 continue;
1775 const APInt &CInt = C->getAPIntValue();
1776 if (CInt.getBoolValue())
1777 MaxFactor = CInt.countTrailingZeros();
1778 }
1779 return MaxFactor;
1780 }
1781 if (Val.getOpcode() == ISD::SHL) {
1782 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1783 return 0;
1784 return (unsigned) Val.getConstantOperandVal(1);
1785 }
1786
1787 return 0;
1788}
1789
1790/// @returns true if V>>Amount will eliminate V's operation on its child
1791static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1792 if (V.getOpcode() == ISD::MUL) {
1793 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001794 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001795 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001796 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001797 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1798 return (NewConst == 1);
1799 }
1800 } else if (V.getOpcode() == ISD::SHL) {
1801 return (Amount == V.getConstantOperandVal(1));
1802 }
1803
1804 return false;
1805}
1806
1807SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1808 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1809 if (V.getOpcode() == ISD::MUL) {
1810 for (int i=0; i < 2; ++i) {
1811 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1812 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1813 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1814 if (NewConst == 1)
1815 return Ops[!i];
1816 Ops[i] = CurDAG->getConstant(NewConst,
1817 SDLoc(V), V.getValueType());
1818 break;
1819 }
1820 }
1821 } else if (V.getOpcode() == ISD::SHL) {
1822 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1823 if (ShiftAmount == Power)
1824 return Ops[0];
1825 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1826 SDLoc(V), V.getValueType());
1827 }
1828
1829 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1830}
1831
1832static bool isTargetConstant(const SDValue &V) {
1833 return V.getOpcode() == HexagonISD::CONST32 ||
1834 V.getOpcode() == HexagonISD::CONST32_GP;
1835}
1836
1837unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1838 if (GAUsesInFunction.count(V))
1839 return GAUsesInFunction[V];
1840
1841 unsigned Result = 0;
Matthias Braunf1caa282017-12-15 22:22:58 +00001842 const Function &CurF = CurDAG->getMachineFunction().getFunction();
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001843 for (const User *U : V->users()) {
1844 if (isa<Instruction>(U) &&
Matthias Braunf1caa282017-12-15 22:22:58 +00001845 cast<Instruction>(U)->getParent()->getParent() == &CurF)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001846 ++Result;
1847 }
1848
1849 GAUsesInFunction[V] = Result;
1850
1851 return Result;
1852}
1853
1854/// Note - After calling this, N may be dead. It may have been replaced by a
1855/// new node, so always use the returned value in place of N.
1856///
1857/// @returns The SDValue taking the place of N (which could be N if it is
1858/// unchanged)
1859SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1860 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1861 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1862 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1863
1864 // Return early if this node was already visited
1865 if (RootWeights[N] != -1)
1866 return SDValue(N, 0);
1867
1868 assert(isOpcodeHandled(N));
1869
1870 SDValue Op0 = N->getOperand(0);
1871 SDValue Op1 = N->getOperand(1);
1872
1873 // Return early if the operands will remain unchanged or are all roots
1874 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1875 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1876 SDNode *Op0N = Op0.getNode();
1877 int Weight;
1878 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1879 Weight = getWeight(balanceSubTree(Op0N).getNode());
1880 // Weight = calculateWeight(Op0N);
1881 } else
1882 Weight = getWeight(Op0N);
1883
1884 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1885 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1886 Weight += getWeight(balanceSubTree(Op1N).getNode());
1887 // Weight += calculateWeight(Op1N);
1888 } else
1889 Weight += getWeight(Op1N);
1890
1891 RootWeights[N] = Weight;
1892 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1893 getHeight(N->getOperand(1).getNode())) + 1;
1894
1895 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1896 << " Height=" << RootHeights[N] << "): ");
Krzysztof Parzyszek1ca23d92018-03-30 14:29:15 +00001897 DEBUG(N->dump(CurDAG));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001898
1899 return SDValue(N, 0);
1900 }
1901
1902 DEBUG(dbgs() << "** Balancing root node: ");
Krzysztof Parzyszek1ca23d92018-03-30 14:29:15 +00001903 DEBUG(N->dump(CurDAG));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001904
1905 unsigned NOpcode = N->getOpcode();
1906
1907 LeafPrioQueue Leaves(NOpcode);
1908 SmallVector<SDValue, 4> Worklist;
1909 Worklist.push_back(SDValue(N, 0));
1910
1911 // SHL nodes will be converted to MUL nodes
1912 if (NOpcode == ISD::SHL)
1913 NOpcode = ISD::MUL;
1914
1915 bool CanFactorize = false;
1916 WeightedLeaf Mul1, Mul2;
1917 unsigned MaxPowerOf2 = 0;
1918 WeightedLeaf GA;
1919
1920 // Do not try to factor out a shift if there is already a shift at the tip of
1921 // the tree.
1922 bool HaveTopLevelShift = false;
1923 if (TopLevel &&
1924 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1925 Op0.getConstantOperandVal(1) < 4) ||
1926 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1927 Op1.getConstantOperandVal(1) < 4)))
1928 HaveTopLevelShift = true;
1929
1930 // Flatten the subtree into an ordered list of leaves; at the same time
1931 // determine whether the tree is already balanced.
1932 int InsertionOrder = 0;
1933 SmallDenseMap<SDValue, int> NodeHeights;
1934 bool Imbalanced = false;
1935 int CurrentWeight = 0;
1936 while (!Worklist.empty()) {
1937 SDValue Child = Worklist.pop_back_val();
1938
1939 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1940 // CASE 1: Child is a root note
1941
1942 int Weight = RootWeights[Child.getNode()];
1943 if (Weight == -1) {
1944 Child = balanceSubTree(Child.getNode());
1945 // calculateWeight(Child.getNode());
1946 Weight = getWeight(Child.getNode());
1947 } else if (Weight == -2) {
1948 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1949 // made. Our worklist isn't up to date anymore.
1950 // Restart the whole process.
1951 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1952 return balanceSubTree(N, TopLevel);
1953 }
1954
1955 NodeHeights[Child] = 1;
1956 CurrentWeight += Weight;
1957
1958 unsigned PowerOf2;
1959 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1960 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1961 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1962 // Try to identify two factorizable MUL/SHL children greedily. Leave
1963 // them out of the priority queue for now so we can deal with them
1964 // after.
1965 if (!Mul1.Value.getNode()) {
1966 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1967 MaxPowerOf2 = PowerOf2;
1968 } else {
1969 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1970 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1971
1972 // Our addressing modes can only shift by a maximum of 3
1973 if (MaxPowerOf2 > 3)
1974 MaxPowerOf2 = 3;
1975
1976 CanFactorize = true;
1977 }
1978 } else
1979 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1980 } else if (!isOpcodeHandled(Child.getNode())) {
1981 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1982 int Weight = getWeight(Child.getNode());
1983
1984 NodeHeights[Child] = getHeight(Child.getNode());
1985 CurrentWeight += Weight;
1986
1987 if (isTargetConstant(Child) && !GA.Value.getNode())
1988 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1989 else
1990 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1991 } else {
1992 // CASE 3: Child is a subtree of same opcode
1993 // Visit children first, then flatten.
1994 unsigned ChildOpcode = Child.getOpcode();
1995 assert(ChildOpcode == NOpcode ||
1996 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1997
1998 // Convert SHL to MUL
1999 SDValue Op1;
2000 if (ChildOpcode == ISD::SHL)
2001 Op1 = getMultiplierForSHL(Child.getNode());
2002 else
2003 Op1 = Child->getOperand(1);
2004
2005 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
2006 assert(!NodeHeights.count(Child) && "Parent visited before children?");
2007 // Visit children first, then re-visit this node
2008 Worklist.push_back(Child);
2009 Worklist.push_back(Op1);
2010 Worklist.push_back(Child->getOperand(0));
2011 } else {
2012 // Back at this node after visiting the children
2013 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
2014 Imbalanced = true;
2015
2016 NodeHeights[Child] = std::max(NodeHeights[Op1],
2017 NodeHeights[Child->getOperand(0)]) + 1;
2018 }
2019 }
2020 }
2021
2022 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
2023 << " weight=" << CurrentWeight << " imbalanced="
2024 << Imbalanced << "\n");
2025
2026 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
2027 // This factors out a shift in order to match memw(a<<Y+b).
2028 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
2029 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
2030 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
2031 int Weight = Mul1.Weight + Mul2.Weight;
2032 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
2033 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
2034 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
2035 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
2036 Mul1Factored, Mul2Factored);
2037 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
2038 Mul1.Value.getValueType());
2039 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
2040 Sum, Const);
2041 NodeHeights[New] = Height;
2042 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
2043 } else if (Mul1.Value.getNode()) {
2044 // We failed to factorize two MULs, so now the Muls are left outside the
2045 // queue... add them back.
2046 Leaves.push(Mul1);
2047 if (Mul2.Value.getNode())
2048 Leaves.push(Mul2);
2049 CanFactorize = false;
2050 }
2051
2052 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
2053 // and the root node itself is not used more than twice. This reduces the
2054 // amount of additional constant extenders introduced by this optimization.
2055 bool CombinedGA = false;
2056 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
2057 GA.Value.hasOneUse() && N->use_size() < 3) {
2058 GlobalAddressSDNode *GANode =
2059 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
2060 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
2061
2062 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
2063 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
2064 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
2065 << "): ");
Krzysztof Parzyszek1ca23d92018-03-30 14:29:15 +00002066 DEBUG(GANode->dump(CurDAG));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002067
2068 SDValue NewTGA =
2069 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
2070 GANode->getValueType(0),
2071 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
2072 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
2073 GA.Value.getValueType(), NewTGA);
2074 GA.Weight += Leaves.top().Weight;
2075
2076 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
2077 CombinedGA = true;
2078
2079 Leaves.pop(); // Remove the offset constant from the queue
2080 }
2081 }
2082
2083 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
2084 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
2085 RootWeights[N] = CurrentWeight;
2086 RootHeights[N] = NodeHeights[SDValue(N, 0)];
2087
2088 return SDValue(N, 0);
2089 }
2090
2091 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
2092 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
2093 WeightedLeaf SHL = Leaves.findSHL(31);
2094 if (SHL.Value.getNode()) {
2095 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2096 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2097 GA.Value.getValueType(),
2098 GA.Value, SHL.Value);
2099 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2100 NodeHeights[GA.Value] = Height;
2101 }
2102 }
2103
2104 if (GA.Value.getNode())
2105 Leaves.push(GA);
2106
2107 // If this is the top level and we haven't factored out a shift, we should try
2108 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2109 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2110 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2111 Leaves.pushToBottom(Leaves.pop());
2112 }
2113
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002114 const DataLayout &DL = CurDAG->getDataLayout();
2115 const TargetLowering &TLI = *getTargetLowering();
2116
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002117 // Rebuild the tree using Huffman's algorithm
2118 while (Leaves.size() > 1) {
2119 WeightedLeaf L0 = Leaves.pop();
2120
2121 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2122 // otherwise just get the next leaf
2123 WeightedLeaf L1 = Leaves.findMULbyConst();
2124 if (!L1.Value.getNode())
2125 L1 = Leaves.pop();
2126
2127 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2128
2129 SDValue V0 = L0.Value;
2130 int V0Weight = L0.Weight;
2131 SDValue V1 = L1.Value;
2132 int V1Weight = L1.Weight;
2133
2134 // Make sure that none of these nodes have been RAUW'd
2135 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2136 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2137 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2138 return balanceSubTree(N, TopLevel);
2139 }
2140
2141 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2142 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2143 EVT VT = N->getValueType(0);
2144 SDValue NewNode;
2145
2146 if (V0C && !V1C) {
2147 std::swap(V0, V1);
2148 std::swap(V0C, V1C);
2149 }
2150
2151 // Calculate height of this node
2152 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2153 "Children must have been visited before re-combining them!");
2154 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2155
2156 // Rebuild this node (and restore SHL from MUL if needed)
2157 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2158 NewNode = CurDAG->getNode(
2159 ISD::SHL, SDLoc(V0), VT, V0,
2160 CurDAG->getConstant(
2161 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002162 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002163 else
2164 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2165
2166 NodeHeights[NewNode] = Height;
2167
2168 int Weight = V0Weight + V1Weight;
2169 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2170
2171 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2172 << Height << "):\n");
2173 DEBUG(NewNode.dump());
2174 }
2175
2176 assert(Leaves.size() == 1);
2177 SDValue NewRoot = Leaves.top().Value;
2178
2179 assert(NodeHeights.count(NewRoot));
2180 int Height = NodeHeights[NewRoot];
2181
2182 // Restore SHL if we earlier converted it to a MUL
2183 if (NewRoot.getOpcode() == ISD::MUL) {
2184 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2185 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2186 EVT VT = NewRoot.getValueType();
2187 SDValue V0 = NewRoot.getOperand(0);
2188 NewRoot = CurDAG->getNode(
2189 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002190 CurDAG->getConstant(
2191 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2192 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002193 }
2194 }
2195
2196 if (N != NewRoot.getNode()) {
2197 DEBUG(dbgs() << "--> Root is now: ");
2198 DEBUG(NewRoot.dump());
2199
2200 // Replace all uses of old root by new root
2201 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2202 // Mark that we have RAUW'd N
2203 RootWeights[N] = -2;
2204 } else {
2205 DEBUG(dbgs() << "--> Root unchanged.\n");
2206 }
2207
2208 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2209 RootHeights[NewRoot.getNode()] = Height;
2210
2211 return NewRoot;
2212}
2213
2214void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002215 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002216 SDNode *N = &*I++;
2217 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2218 continue;
2219
2220 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2221 if (BasePtr.getOpcode() != ISD::ADD)
2222 continue;
2223
2224 // We've already processed this node
2225 if (RootWeights.count(BasePtr.getNode()))
2226 continue;
2227
2228 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
Krzysztof Parzyszek1ca23d92018-03-30 14:29:15 +00002229 DEBUG(N->dump(CurDAG));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002230
2231 // FindRoots
2232 SmallVector<SDNode *, 4> Worklist;
2233
2234 Worklist.push_back(BasePtr.getOperand(0).getNode());
2235 Worklist.push_back(BasePtr.getOperand(1).getNode());
2236
2237 while (!Worklist.empty()) {
2238 SDNode *N = Worklist.pop_back_val();
2239 unsigned Opcode = N->getOpcode();
2240
2241 if (!isOpcodeHandled(N))
2242 continue;
2243
2244 Worklist.push_back(N->getOperand(0).getNode());
2245 Worklist.push_back(N->getOperand(1).getNode());
2246
2247 // Not a root if it has only one use and same opcode as its parent
2248 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2249 continue;
2250
2251 // This root node has already been processed
2252 if (RootWeights.count(N))
2253 continue;
2254
2255 RootWeights[N] = -1;
2256 }
2257
2258 // Balance node itself
2259 RootWeights[BasePtr.getNode()] = -1;
2260 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2261
2262 if (N->getOpcode() == ISD::LOAD)
2263 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2264 NewBasePtr, N->getOperand(2));
2265 else
2266 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2267 NewBasePtr, N->getOperand(3));
2268
2269 DEBUG(dbgs() << "--> Final node: ");
Krzysztof Parzyszek1ca23d92018-03-30 14:29:15 +00002270 DEBUG(N->dump(CurDAG));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002271 }
2272
2273 CurDAG->RemoveDeadNodes();
2274 GAUsesInFunction.clear();
2275 RootHeights.clear();
2276 RootWeights.clear();
2277}