blob: d0cd143a4d4682ab872115d7ea67b64498ed6d15 [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
Tony Linthicum1213a7a2011-12-12 21:14:40 +000067// Intrinsics that return a a predicate.
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +000068static bool doesIntrinsicReturnPredicate(unsigned ID) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000069 switch (ID) {
70 default:
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +000071 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000072 case Intrinsic::hexagon_C2_cmpeq:
73 case Intrinsic::hexagon_C2_cmpgt:
74 case Intrinsic::hexagon_C2_cmpgtu:
75 case Intrinsic::hexagon_C2_cmpgtup:
76 case Intrinsic::hexagon_C2_cmpgtp:
77 case Intrinsic::hexagon_C2_cmpeqp:
78 case Intrinsic::hexagon_C2_bitsset:
79 case Intrinsic::hexagon_C2_bitsclr:
80 case Intrinsic::hexagon_C2_cmpeqi:
81 case Intrinsic::hexagon_C2_cmpgti:
82 case Intrinsic::hexagon_C2_cmpgtui:
83 case Intrinsic::hexagon_C2_cmpgei:
84 case Intrinsic::hexagon_C2_cmpgeui:
85 case Intrinsic::hexagon_C2_cmplt:
86 case Intrinsic::hexagon_C2_cmpltu:
87 case Intrinsic::hexagon_C2_bitsclri:
88 case Intrinsic::hexagon_C2_and:
89 case Intrinsic::hexagon_C2_or:
90 case Intrinsic::hexagon_C2_xor:
91 case Intrinsic::hexagon_C2_andn:
92 case Intrinsic::hexagon_C2_not:
93 case Intrinsic::hexagon_C2_orn:
94 case Intrinsic::hexagon_C2_pxfer_map:
95 case Intrinsic::hexagon_C2_any8:
96 case Intrinsic::hexagon_C2_all8:
97 case Intrinsic::hexagon_A2_vcmpbeq:
98 case Intrinsic::hexagon_A2_vcmpbgtu:
99 case Intrinsic::hexagon_A2_vcmpheq:
100 case Intrinsic::hexagon_A2_vcmphgt:
101 case Intrinsic::hexagon_A2_vcmphgtu:
102 case Intrinsic::hexagon_A2_vcmpweq:
103 case Intrinsic::hexagon_A2_vcmpwgt:
104 case Intrinsic::hexagon_A2_vcmpwgtu:
105 case Intrinsic::hexagon_C2_tfrrp:
106 case Intrinsic::hexagon_S2_tstbit_i:
107 case Intrinsic::hexagon_S2_tstbit_r:
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000108 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000109 }
110}
111
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000112void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000113 SDValue Chain = LD->getChain();
114 SDValue Base = LD->getBasePtr();
115 SDValue Offset = LD->getOffset();
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000116 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000117 EVT LoadedVT = LD->getMemoryVT();
118 unsigned Opcode = 0;
119
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000120 // Check for zero extended loads. Treat any-extend loads as zero extended
121 // loads.
122 ISD::LoadExtType ExtType = LD->getExtensionType();
123 bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000124 bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000125
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000126 assert(LoadedVT.isSimple());
127 switch (LoadedVT.getSimpleVT().SimpleTy) {
128 case MVT::i8:
129 if (IsZeroExt)
130 Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000131 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000132 Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
133 break;
134 case MVT::i16:
135 if (IsZeroExt)
136 Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000137 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000138 Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
139 break;
140 case MVT::i32:
141 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
142 break;
143 case MVT::i64:
144 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
145 break;
146 // 64B
147 case MVT::v64i8:
148 case MVT::v32i16:
149 case MVT::v16i32:
150 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000151 case MVT::v128i8:
152 case MVT::v64i16:
153 case MVT::v32i32:
154 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000155 if (isAlignedMemNode(LD)) {
156 if (LD->isNonTemporal())
157 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
158 else
159 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
160 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000161 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000162 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000163 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000164 default:
165 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000166 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000167
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000168 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
169 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
170 MemOp[0] = LD->getMemOperand();
171
172 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
173 -> MachineSDNode* {
174 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
175 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
176 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
177 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000178 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000179 if (ExtType == ISD::SEXTLOAD)
180 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
181 SDValue(N, 0));
182 return N;
183 };
184
185 // Loaded value Next address Chain
186 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
187 SDValue To[3];
188
189 EVT ValueVT = LD->getValueType(0);
190 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
191 // A load extending to i64 will actually produce i32, which will then
192 // need to be extended to i64.
193 assert(LoadedVT.getSizeInBits() <= 32);
194 ValueVT = MVT::i32;
195 }
196
197 if (IsValidInc) {
198 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
199 MVT::i32, MVT::Other, Base,
200 IncV, Chain);
201 L->setMemRefs(MemOp, MemOp+1);
202 To[1] = SDValue(L, 1); // Next address.
203 To[2] = SDValue(L, 2); // Chain.
204 // Handle special case for extension to i64.
205 if (LD->getValueType(0) == MVT::i64)
206 L = getExt64(L, dl);
207 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000208 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000209 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
210 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
211 Base, Zero, Chain);
212 L->setMemRefs(MemOp, MemOp+1);
213 To[2] = SDValue(L, 1); // Chain.
214 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
215 Base, IncV);
216 To[1] = SDValue(A, 0); // Next address.
217 // Handle special case for extension to i64.
218 if (LD->getValueType(0) == MVT::i64)
219 L = getExt64(L, dl);
220 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000221 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000222 ReplaceUses(From, To, 3);
223 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000224}
225
226
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000227MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
228 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
229 return nullptr;
230
231 SDLoc dl(IntN);
232 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
233
234 static std::map<unsigned,unsigned> LoadPciMap = {
235 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
236 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
237 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
238 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
239 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
240 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
241 };
242 auto FLC = LoadPciMap.find(IntNo);
243 if (FLC != LoadPciMap.end()) {
244 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
245 IntN->getOperand(4));
246 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
247 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
248 // Operands: { Base, Increment, Modifier, Chain }
249 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
250 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
251 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
252 { IntN->getOperand(2), I, SDValue(Mod,0), IntN->getOperand(0) });
253 return Res;
254 }
255
256 static std::map<unsigned,unsigned> LoadPbrMap = {
257 { Intrinsic::hexagon_brev_ldb, Hexagon::L2_loadrb_pbr },
258 { Intrinsic::hexagon_brev_ldub, Hexagon::L2_loadrub_pbr },
259 { Intrinsic::hexagon_brev_ldh, Hexagon::L2_loadrh_pbr },
260 { Intrinsic::hexagon_brev_lduh, Hexagon::L2_loadruh_pbr },
261 { Intrinsic::hexagon_brev_ldw, Hexagon::L2_loadri_pbr },
262 { Intrinsic::hexagon_brev_ldd, Hexagon::L2_loadrd_pbr },
263 };
264 auto FLB = LoadPbrMap.find(IntNo);
265 if (FLB != LoadPbrMap.end()) {
266 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
267 IntN->getOperand(4));
268 EVT ValTy = (IntNo == Intrinsic::hexagon_brev_ldd) ? MVT::i64 : MVT::i32;
269 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
270 // Operands: { Base, Modifier, Chain }
271 MachineSDNode *Res = CurDAG->getMachineNode(FLB->second, dl, RTys,
272 { IntN->getOperand(2), SDValue(Mod,0), IntN->getOperand(0) });
273 return Res;
274 }
275
276 return nullptr;
277}
278
279SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
280 SDNode *IntN) {
281 // The "LoadN" is just a machine load instruction. The intrinsic also
282 // involves storing it. Generate an appropriate store to the location
283 // given in the intrinsic's operand(3).
284 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
285 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
286 HexagonII::MemAccesSizeMask;
287 unsigned Size = 1U << (SizeBits-1);
288
289 SDLoc dl(IntN);
290 MachinePointerInfo PI;
291 SDValue TS;
292 SDValue Loc = IntN->getOperand(3);
293
294 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000295 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
296 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000297 else
Justin Lebar9c375812016-07-15 18:27:10 +0000298 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
299 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000300
301 SDNode *StoreN;
302 {
303 HandleSDNode Handle(TS);
304 SelectStore(TS.getNode());
305 StoreN = Handle.getValue().getNode();
306 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000307
308 // Load's results are { Loaded value, Updated pointer, Chain }
309 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
310 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
311 return StoreN;
312}
313
Justin Bognerec37a022016-05-12 21:46:18 +0000314bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000315 // The intrinsics for load circ/brev perform two operations:
316 // 1. Load a value V from the specified location, using the addressing
317 // mode corresponding to the intrinsic.
318 // 2. Store V into a specified location. This location is typically a
319 // local, temporary object.
320 // In many cases, the program using these intrinsics will immediately
321 // load V again from the local object. In those cases, when certain
322 // conditions are met, the last load can be removed.
323 // This function identifies and optimizes this pattern. If the pattern
324 // cannot be optimized, it returns nullptr, which will cause the load
325 // to be selected separately from the intrinsic (which will be handled
326 // in SelectIntrinsicWChain).
327
328 SDValue Ch = N->getOperand(0);
329 SDValue Loc = N->getOperand(1);
330
331 // Assume that the load and the intrinsic are connected directly with a
332 // chain:
333 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
334 // t2: i32,ch = load t1:1, Loc, ...
335 SDNode *C = Ch.getNode();
336
337 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000338 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000339
340 // The second load can only be eliminated if its extension type matches
341 // that of the load instruction corresponding to the intrinsic. The user
342 // can provide an address of an unsigned variable to store the result of
343 // a sign-extending intrinsic into (or the other way around).
344 ISD::LoadExtType IntExt;
345 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
346 case Intrinsic::hexagon_brev_ldub:
347 case Intrinsic::hexagon_brev_lduh:
348 case Intrinsic::hexagon_circ_ldub:
349 case Intrinsic::hexagon_circ_lduh:
350 IntExt = ISD::ZEXTLOAD;
351 break;
352 case Intrinsic::hexagon_brev_ldw:
353 case Intrinsic::hexagon_brev_ldd:
354 case Intrinsic::hexagon_circ_ldw:
355 case Intrinsic::hexagon_circ_ldd:
356 IntExt = ISD::NON_EXTLOAD;
357 break;
358 default:
359 IntExt = ISD::SEXTLOAD;
360 break;
361 }
362 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000363 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000364
365 // Make sure the target location for the loaded value in the load intrinsic
366 // is the location from which LD (or N) is loading.
367 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000368 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000369
370 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
371 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
372 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
373 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
374 ReplaceUses(F, T, array_lengthof(T));
375 // This transformation will leave the intrinsic dead. If it remains in
376 // the DAG, the selection code will see it again, but without the load,
377 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000378 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000379 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000380 }
381
Justin Bognerec37a022016-05-12 21:46:18 +0000382 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000383}
384
Justin Bognerec37a022016-05-12 21:46:18 +0000385void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000386 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000387 LoadSDNode *LD = cast<LoadSDNode>(N);
388 ISD::MemIndexedMode AM = LD->getAddressingMode();
389
390 // Handle indexed loads.
Justin Bognerec37a022016-05-12 21:46:18 +0000391 if (AM != ISD::UNINDEXED) {
392 SelectIndexedLoad(LD, dl);
393 return;
394 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000395
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000396 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000397 if (tryLoadOfLoadIntrinsic(LD))
398 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000399
Justin Bognerec37a022016-05-12 21:46:18 +0000400 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000401}
402
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000403void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000404 SDValue Chain = ST->getChain();
405 SDValue Base = ST->getBasePtr();
406 SDValue Offset = ST->getOffset();
407 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000408 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000409 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000410 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000411 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000412
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000413 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000414 unsigned Opcode = 0;
415
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000416 assert(StoredVT.isSimple());
417 switch (StoredVT.getSimpleVT().SimpleTy) {
418 case MVT::i8:
419 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
420 break;
421 case MVT::i16:
422 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
423 break;
424 case MVT::i32:
425 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
426 break;
427 case MVT::i64:
428 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
429 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000430 case MVT::v64i8:
431 case MVT::v32i16:
432 case MVT::v16i32:
433 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000434 case MVT::v128i8:
435 case MVT::v64i16:
436 case MVT::v32i32:
437 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000438 if (isAlignedMemNode(ST)) {
439 if (ST->isNonTemporal())
440 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
441 else
442 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
443 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000444 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000445 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000446 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000447 default:
448 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000449 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000450
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000451 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
452 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000453 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000454 dl, MVT::i32, Value);
455 }
456
457 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000458 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
459 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000460
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000461 // Next address Chain
462 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
463 SDValue To[2];
464
465 if (IsValidInc) {
466 // Build post increment store.
467 SDValue Ops[] = { Base, IncV, Value, Chain };
468 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
469 Ops);
470 S->setMemRefs(MemOp, MemOp + 1);
471 To[0] = SDValue(S, 0);
472 To[1] = SDValue(S, 1);
473 } else {
474 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
475 SDValue Ops[] = { Base, Zero, Value, Chain };
476 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
477 S->setMemRefs(MemOp, MemOp + 1);
478 To[1] = SDValue(S, 0);
479 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
480 Base, IncV);
481 To[0] = SDValue(A, 0);
482 }
483
484 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000485 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000486}
487
Justin Bognerec37a022016-05-12 21:46:18 +0000488void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000489 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000490 StoreSDNode *ST = cast<StoreSDNode>(N);
491 ISD::MemIndexedMode AM = ST->getAddressingMode();
492
493 // Handle indexed stores.
494 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000495 SelectIndexedStore(ST, dl);
496 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000497 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000498
Justin Bognerec37a022016-05-12 21:46:18 +0000499 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000500}
501
Justin Bognerec37a022016-05-12 21:46:18 +0000502void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000503 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000504 SDValue Shl_0 = N->getOperand(0);
505 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000506
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000507 auto Default = [this,N] () -> void { SelectCode(N); };
508
509 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
510 return Default();
511
512 // RHS is const.
513 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
514
515 if (Shl_0.getOpcode() == ISD::MUL) {
516 SDValue Mul_0 = Shl_0.getOperand(0); // Val
517 SDValue Mul_1 = Shl_0.getOperand(1); // Const
518 // RHS of mul is const.
519 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
520 int32_t ValConst = C->getSExtValue() << ShlConst;
521 if (isInt<9>(ValConst)) {
522 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
523 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
524 MVT::i32, Mul_0, Val);
525 ReplaceNode(N, Result);
526 return;
527 }
528 }
529 return Default();
530 }
531
532 if (Shl_0.getOpcode() == ISD::SUB) {
533 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
534 SDValue Sub_1 = Shl_0.getOperand(1); // Val
535 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
536 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
537 return Default();
538 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
539 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
540 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
541 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
542 if (isInt<9>(-ValConst)) {
543 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
544 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
545 MVT::i32, Shl2_0, Val);
546 ReplaceNode(N, Result);
547 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000548 }
549 }
550 }
551 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000552
553 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000554}
555
556
557//
558// If there is an zero_extend followed an intrinsic in DAG (this means - the
559// result of the intrinsic is predicate); convert the zero_extend to
560// transfer instruction.
561//
562// Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
563// converted into a MUX as predicate registers defined as 1 bit in the
564// compiler. Architecture defines them as 8-bit registers.
565// We want to preserve all the lower 8-bits and, not just 1 LSB bit.
566//
Justin Bognerec37a022016-05-12 21:46:18 +0000567void HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000568 SDLoc dl(N);
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000569
570 SDValue Op0 = N->getOperand(0);
571 EVT OpVT = Op0.getValueType();
572 unsigned OpBW = OpVT.getSizeInBits();
573
574 // Special handling for zero-extending a vector of booleans.
575 if (OpVT.isVector() && OpVT.getVectorElementType() == MVT::i1 && OpBW <= 64) {
576 SDNode *Mask = CurDAG->getMachineNode(Hexagon::C2_mask, dl, MVT::i64, Op0);
577 unsigned NE = OpVT.getVectorNumElements();
578 EVT ExVT = N->getValueType(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +0000579 unsigned ES = ExVT.getScalarSizeInBits();
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000580 uint64_t MV = 0, Bit = 1;
581 for (unsigned i = 0; i < NE; ++i) {
582 MV |= Bit;
583 Bit <<= ES;
584 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000585 SDValue Ones = CurDAG->getTargetConstant(MV, dl, MVT::i64);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000586 SDNode *OnesReg = CurDAG->getMachineNode(Hexagon::CONST64, dl,
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000587 MVT::i64, Ones);
588 if (ExVT.getSizeInBits() == 32) {
589 SDNode *And = CurDAG->getMachineNode(Hexagon::A2_andp, dl, MVT::i64,
590 SDValue(Mask,0), SDValue(OnesReg,0));
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000591 SDValue SubR = CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32);
Justin Bognerec37a022016-05-12 21:46:18 +0000592 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::EXTRACT_SUBREG, dl, ExVT,
593 SDValue(And, 0), SubR));
594 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000595 }
Justin Bognerec37a022016-05-12 21:46:18 +0000596 ReplaceNode(N,
597 CurDAG->getMachineNode(Hexagon::A2_andp, dl, ExVT,
598 SDValue(Mask, 0), SDValue(OnesReg, 0)));
599 return;
Krzysztof Parzyszek42113342015-03-19 16:33:08 +0000600 }
601
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000602 SDNode *Int = N->getOperand(0).getNode();
603 if ((Int->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
604 unsigned ID = cast<ConstantSDNode>(Int->getOperand(0))->getZExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000605 if (doesIntrinsicReturnPredicate(ID)) {
606 // Now we need to differentiate target data types.
607 if (N->getValueType(0) == MVT::i64) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000608 // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000609 SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000610 SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000611 MVT::i32, SDValue(Int, 0));
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000612 SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000613 MVT::i32, TargetConst0);
Colin LeMahieub580d7d2014-12-09 19:23:45 +0000614 SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000615 MVT::i64, MVT::Other,
616 SDValue(Result_2, 0),
617 SDValue(Result_1, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000618 ReplaceNode(N, Result_3);
619 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000620 }
621 if (N->getValueType(0) == MVT::i32) {
622 // Convert the zero_extend to Rs = Pd
Colin LeMahieu30dcb232014-12-09 18:16:49 +0000623 SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000624 MVT::i32, SDValue(Int, 0));
Justin Bognerec37a022016-05-12 21:46:18 +0000625 ReplaceNode(N, RsPd);
626 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000627 }
Craig Toppere55c5562012-02-07 02:50:20 +0000628 llvm_unreachable("Unexpected value type");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000629 }
630 }
Justin Bognerec37a022016-05-12 21:46:18 +0000631 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000632}
633
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000634
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000635//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000636// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000637//
Justin Bognerec37a022016-05-12 21:46:18 +0000638void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
639 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
640 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000641 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000642 return;
643 }
644 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000645}
646
Justin Bognerec37a022016-05-12 21:46:18 +0000647void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000648 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
649 unsigned Bits;
650 switch (IID) {
651 case Intrinsic::hexagon_S2_vsplatrb:
652 Bits = 8;
653 break;
654 case Intrinsic::hexagon_S2_vsplatrh:
655 Bits = 16;
656 break;
657 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000658 SelectCode(N);
659 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000660 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000661
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000662 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000663 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000664 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000665 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000666 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000667 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000668 SelectCode(R.getNode());
669 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000670 }
Justin Bognerec37a022016-05-12 21:46:18 +0000671 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000672}
673
Sirish Pande69295b82012-05-10 20:20:25 +0000674//
675// Map floating point constant values.
676//
Justin Bognerec37a022016-05-12 21:46:18 +0000677void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000678 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000679 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000680 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000681 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000682 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
683 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000684 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000685 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000686 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000687 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
688 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000689 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000690 }
691
Justin Bognerec37a022016-05-12 21:46:18 +0000692 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000693}
694
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000695//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000696// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000697//
Justin Bognerec37a022016-05-12 21:46:18 +0000698void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000699 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000700 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
701 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
702 ? Hexagon::PS_true
703 : Hexagon::PS_false;
704 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
705 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000706 }
707
Justin Bognerec37a022016-05-12 21:46:18 +0000708 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000709}
710
711
Justin Bognerec37a022016-05-12 21:46:18 +0000712void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000713 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000714 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000715 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000716 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000717 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000718 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000719 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000720 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000721 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000722
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000723 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000724 // - the object is fixed, or
725 // - there are no objects with higher-than-default alignment, or
726 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000727 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000728 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000729 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000730 } else {
731 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
732 unsigned AR = HMFI.getStackAlignBaseVReg();
733 SDValue CH = CurDAG->getEntryNode();
734 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000735 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000736 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000737
Justin Bognerec37a022016-05-12 21:46:18 +0000738 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000739}
740
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000741
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000742void HexagonDAGToDAGISel::SelectBitcast(SDNode *N) {
743 EVT SVT = N->getOperand(0).getValueType();
744 EVT DVT = N->getValueType(0);
745 if (!SVT.isVector() || !DVT.isVector() ||
746 SVT.getVectorElementType() == MVT::i1 ||
747 DVT.getVectorElementType() == MVT::i1 ||
748 SVT.getSizeInBits() != DVT.getSizeInBits()) {
749 SelectCode(N);
750 return;
751 }
752
753 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N,0), N->getOperand(0));
754 CurDAG->RemoveDeadNode(N);
755}
756
Justin Bognerec37a022016-05-12 21:46:18 +0000757void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000758 if (N->isMachineOpcode())
759 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000760
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000761 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000762 case ISD::Constant: return SelectConstant(N);
763 case ISD::ConstantFP: return SelectConstantFP(N);
764 case ISD::FrameIndex: return SelectFrameIndex(N);
765 case ISD::BITCAST: return SelectBitcast(N);
766 case ISD::SHL: return SelectSHL(N);
767 case ISD::LOAD: return SelectLoad(N);
768 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000769 case ISD::ZERO_EXTEND: return SelectZeroExtend(N);
770 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
771 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000772 }
773
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000774 if (HST->useHVXOps()) {
775 switch (N->getOpcode()) {
776 case ISD::VECTOR_SHUFFLE: return SelectHvxShuffle(N);
777 case HexagonISD::VROR: return SelectHvxRor(N);
778 }
779 }
780
Justin Bognerec37a022016-05-12 21:46:18 +0000781 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000782}
783
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000784bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000785SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000786 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000787 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000788
Daniel Sanders60f1db02015-03-13 12:45:09 +0000789 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000790 default:
791 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000792 case InlineAsm::Constraint_i:
793 case InlineAsm::Constraint_o: // Offsetable.
794 case InlineAsm::Constraint_v: // Not offsetable.
795 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000796 if (SelectAddrFI(Inp, Res))
797 OutOps.push_back(Res);
798 else
799 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000800 break;
801 }
802
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000803 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000804 return false;
805}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000806
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000807
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000808static bool isMemOPCandidate(SDNode *I, SDNode *U) {
809 // I is an operand of U. Check if U is an arithmetic (binary) operation
810 // usable in a memop, where the other operand is a loaded value, and the
811 // result of U is stored in the same location.
812
813 if (!U->hasOneUse())
814 return false;
815 unsigned Opc = U->getOpcode();
816 switch (Opc) {
817 case ISD::ADD:
818 case ISD::SUB:
819 case ISD::AND:
820 case ISD::OR:
821 break;
822 default:
823 return false;
824 }
825
826 SDValue S0 = U->getOperand(0);
827 SDValue S1 = U->getOperand(1);
828 SDValue SY = (S0.getNode() == I) ? S1 : S0;
829
830 SDNode *UUse = *U->use_begin();
831 if (UUse->getNumValues() != 1)
832 return false;
833
834 // Check if one of the inputs to U is a load instruction and the output
835 // is used by a store instruction. If so and they also have the same
836 // base pointer, then don't preoprocess this node sequence as it
837 // can be matched to a memop.
838 SDNode *SYNode = SY.getNode();
839 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
840 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
841 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
842 if (LDBasePtr == STBasePtr)
843 return true;
844 }
845 return false;
846}
847
848
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000849// Transform: (or (select c x 0) z) -> (select c (or x z) z)
850// (or (select c 0 y) z) -> (select c z (or y z))
851void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000852 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000853
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000854 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000855 if (I->getOpcode() != ISD::OR)
856 continue;
857
858 auto IsZero = [] (const SDValue &V) -> bool {
859 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
860 return SC->isNullValue();
861 return false;
862 };
863 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
864 if (Op.getOpcode() != ISD::SELECT)
865 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000866 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000867 };
868
869 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
870 EVT VT = I->getValueType(0);
871 bool SelN0 = IsSelect0(N0);
872 SDValue SOp = SelN0 ? N0 : N1;
873 SDValue VOp = SelN0 ? N1 : N0;
874
875 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
876 SDValue SC = SOp.getOperand(0);
877 SDValue SX = SOp.getOperand(1);
878 SDValue SY = SOp.getOperand(2);
879 SDLoc DLS = SOp;
880 if (IsZero(SY)) {
881 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
882 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
883 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
884 } else if (IsZero(SX)) {
885 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
886 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
887 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
888 }
889 }
890 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000891}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000892
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000893// Transform: (store ch val (add x (add (shl y c) e)))
894// to: (store ch val (add x (shl (add y d) c))),
895// where e = (shl d c) for some integer d.
896// The purpose of this is to enable generation of loads/stores with
897// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
898// value c must be 0, 1 or 2.
899void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
900 SelectionDAG &DAG = *CurDAG;
901
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000902 for (auto I : Nodes) {
903 if (I->getOpcode() != ISD::STORE)
904 continue;
905
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000906 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000907 SDValue Off = I->getOperand(2);
908 // Off needs to match: (add x (add (shl y c) (shl d c))))
909 if (Off.getOpcode() != ISD::ADD)
910 continue;
911 // Off matched: (add x T0)
912 SDValue T0 = Off.getOperand(1);
913 // T0 needs to match: (add T1 T2):
914 if (T0.getOpcode() != ISD::ADD)
915 continue;
916 // T0 matched: (add T1 T2)
917 SDValue T1 = T0.getOperand(0);
918 SDValue T2 = T0.getOperand(1);
919 // T1 needs to match: (shl y c)
920 if (T1.getOpcode() != ISD::SHL)
921 continue;
922 SDValue C = T1.getOperand(1);
923 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
924 if (CN == nullptr)
925 continue;
926 unsigned CV = CN->getZExtValue();
927 if (CV > 2)
928 continue;
929 // T2 needs to match e, where e = (shl d c) for some d.
930 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
931 if (EN == nullptr)
932 continue;
933 unsigned EV = EN->getZExtValue();
934 if (EV % (1 << CV) != 0)
935 continue;
936 unsigned DV = EV / (1 << CV);
937
938 // Replace T0 with: (shl (add y d) c)
939 SDLoc DL = SDLoc(I);
940 EVT VT = T0.getValueType();
941 SDValue D = DAG.getConstant(DV, DL, VT);
942 // NewAdd = (add y d)
943 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
944 // NewShl = (shl NewAdd c)
945 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
946 ReplaceNode(T0.getNode(), NewShl.getNode());
947 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000948}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +0000949
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000950// Transform: (load ch (add x (and (srl y c) Mask)))
951// to: (load ch (add x (shl (srl y d) d-c)))
952// where
953// Mask = 00..0 111..1 0.0
954// | | +-- d-c 0s, and d-c is 0, 1 or 2.
955// | +-------- 1s
956// +-------------- at most c 0s
957// Motivating example:
958// DAG combiner optimizes (add x (shl (srl y 5) 2))
959// to (add x (and (srl y 3) 1FFFFFFC))
960// which results in a constant-extended and(##...,lsr). This transformation
961// undoes this simplification for cases where the shl can be folded into
962// an addressing mode.
963void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
964 SelectionDAG &DAG = *CurDAG;
965
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000966 for (SDNode *N : Nodes) {
967 unsigned Opc = N->getOpcode();
968 if (Opc != ISD::LOAD && Opc != ISD::STORE)
969 continue;
970 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
971 // Addr must match: (add x T0)
972 if (Addr.getOpcode() != ISD::ADD)
973 continue;
974 SDValue T0 = Addr.getOperand(1);
975 // T0 must match: (and T1 Mask)
976 if (T0.getOpcode() != ISD::AND)
977 continue;
978
979 // We have an AND.
980 //
981 // Check the first operand. It must be: (srl y c).
982 SDValue S = T0.getOperand(0);
983 if (S.getOpcode() != ISD::SRL)
984 continue;
985 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
986 if (SN == nullptr)
987 continue;
988 if (SN->getAPIntValue().getBitWidth() != 32)
989 continue;
990 uint32_t CV = SN->getZExtValue();
991
992 // Check the second operand: the supposed mask.
993 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
994 if (MN == nullptr)
995 continue;
996 if (MN->getAPIntValue().getBitWidth() != 32)
997 continue;
998 uint32_t Mask = MN->getZExtValue();
999 // Examine the mask.
1000 uint32_t TZ = countTrailingZeros(Mask);
1001 uint32_t M1 = countTrailingOnes(Mask >> TZ);
1002 uint32_t LZ = countLeadingZeros(Mask);
1003 // Trailing zeros + middle ones + leading zeros must equal the width.
1004 if (TZ + M1 + LZ != 32)
1005 continue;
1006 // The number of trailing zeros will be encoded in the addressing mode.
1007 if (TZ > 2)
1008 continue;
1009 // The number of leading zeros must be at most c.
1010 if (LZ > CV)
1011 continue;
1012
1013 // All looks good.
1014 SDValue Y = S.getOperand(0);
1015 EVT VT = Addr.getValueType();
1016 SDLoc dl(S);
1017 // TZ = D-C, so D = TZ+C.
1018 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1019 SDValue DC = DAG.getConstant(TZ, dl, VT);
1020 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1021 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1022 ReplaceNode(T0.getNode(), NewShl.getNode());
1023 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001024}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001025
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001026// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1027// (op ... 1 ...))
1028void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1029 SelectionDAG &DAG = *CurDAG;
1030
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001031 for (SDNode *N : Nodes) {
1032 unsigned Opc = N->getOpcode();
1033 if (Opc != ISD::ZERO_EXTEND)
1034 continue;
1035 SDValue OpI1 = N->getOperand(0);
1036 EVT OpVT = OpI1.getValueType();
1037 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1038 continue;
1039 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1040 SDNode *U = *I;
1041 if (U->getNumValues() != 1)
1042 continue;
1043 EVT UVT = U->getValueType(0);
1044 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1045 continue;
1046 if (isMemOPCandidate(N, U))
1047 continue;
1048
1049 // Potentially simplifiable operation.
1050 unsigned I1N = I.getOperandNo();
1051 SmallVector<SDValue,2> Ops(U->getNumOperands());
1052 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1053 Ops[i] = U->getOperand(i);
1054 EVT BVT = Ops[I1N].getValueType();
1055
1056 SDLoc dl(U);
1057 SDValue C0 = DAG.getConstant(0, dl, BVT);
1058 SDValue C1 = DAG.getConstant(1, dl, BVT);
1059 SDValue If0, If1;
1060
1061 if (isa<MachineSDNode>(U)) {
1062 unsigned UseOpc = U->getMachineOpcode();
1063 Ops[I1N] = C0;
1064 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1065 Ops[I1N] = C1;
1066 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1067 } else {
1068 unsigned UseOpc = U->getOpcode();
1069 Ops[I1N] = C0;
1070 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1071 Ops[I1N] = C1;
1072 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1073 }
1074 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1075 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1076 }
1077 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001078}
1079
1080void HexagonDAGToDAGISel::PreprocessISelDAG() {
1081 // Repack all nodes before calling each preprocessing function,
1082 // because each of them can modify the set of nodes.
1083 auto getNodes = [this] () -> std::vector<SDNode*> {
1084 std::vector<SDNode*> T;
1085 T.reserve(CurDAG->allnodes_size());
1086 for (SDNode &N : CurDAG->allnodes())
1087 T.push_back(&N);
1088 return T;
1089 };
1090
1091 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1092 // (or (select c 0 y) z) -> (select c z (or y z))
1093 ppSimplifyOrSelect0(getNodes());
1094
1095 // Transform: (store ch val (add x (add (shl y c) e)))
1096 // to: (store ch val (add x (shl (add y d) c))),
1097 // where e = (shl d c) for some integer d.
1098 // The purpose of this is to enable generation of loads/stores with
1099 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1100 // value c must be 0, 1 or 2.
1101 ppAddrReorderAddShl(getNodes());
1102
1103 // Transform: (load ch (add x (and (srl y c) Mask)))
1104 // to: (load ch (add x (shl (srl y d) d-c)))
1105 // where
1106 // Mask = 00..0 111..1 0.0
1107 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1108 // | +-------- 1s
1109 // +-------------- at most c 0s
1110 // Motivating example:
1111 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1112 // to (add x (and (srl y 3) 1FFFFFFC))
1113 // which results in a constant-extended and(##...,lsr). This transformation
1114 // undoes this simplification for cases where the shl can be folded into
1115 // an addressing mode.
1116 ppAddrRewriteAndSrl(getNodes());
1117
1118 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1119 // (op ... 1 ...))
1120 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001121
1122 DEBUG_WITH_TYPE("isel", {
1123 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1124 CurDAG->dump();
1125 });
1126
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001127 if (EnableAddressRebalancing) {
1128 rebalanceAddressTrees();
1129
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001130 DEBUG_WITH_TYPE("isel", {
1131 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001132 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001133 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001134 }
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001135}
1136
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001137void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1138 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1139 auto &HFI = *HST.getFrameLowering();
1140 if (!HFI.needsAligna(*MF))
1141 return;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001142
Matthias Braun941a7052016-07-28 18:40:00 +00001143 MachineFrameInfo &MFI = MF->getFrameInfo();
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +00001144 MachineBasicBlock *EntryBB = &MF->front();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001145 unsigned AR = FuncInfo->CreateReg(MVT::i32);
Matthias Braun941a7052016-07-28 18:40:00 +00001146 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00001147 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001148 .addImm(MaxA);
1149 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
1150}
1151
1152// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001153bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001154 if (N.getOpcode() != ISD::FrameIndex)
1155 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001156 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001157 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001158 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001159 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001160 return false;
1161 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001162 return true;
1163}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001164
Colin LeMahieu987b0942015-02-04 20:38:01 +00001165inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001166 return SelectGlobalAddress(N, R, false, 0);
Colin LeMahieu987b0942015-02-04 20:38:01 +00001167}
1168
Colin LeMahieu51491352015-02-04 22:36:28 +00001169inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001170 return SelectGlobalAddress(N, R, true, 0);
1171}
1172
1173inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1174 return SelectAnyImmediate(N, R, 0);
1175}
1176
1177inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1178 return SelectAnyImmediate(N, R, 0);
1179}
1180inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1181 return SelectAnyImmediate(N, R, 1);
1182}
1183inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1184 return SelectAnyImmediate(N, R, 2);
1185}
1186inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1187 return SelectAnyImmediate(N, R, 3);
1188}
1189
1190inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1191 EVT T = N.getValueType();
1192 if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1193 return false;
1194 R = N;
1195 return true;
1196}
1197
1198bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1199 uint32_t LogAlign) {
1200 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001201 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001202 };
1203
1204 switch (N.getOpcode()) {
1205 case ISD::Constant: {
1206 if (N.getValueType() != MVT::i32)
1207 return false;
1208 int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1209 if (!IsAligned(V))
1210 return false;
1211 R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1212 return true;
1213 }
1214 case HexagonISD::JT:
1215 case HexagonISD::CP:
1216 // These are assumed to always be aligned at at least 8-byte boundary.
1217 if (LogAlign > 3)
1218 return false;
1219 R = N.getOperand(0);
1220 return true;
1221 case ISD::ExternalSymbol:
1222 // Symbols may be aligned at any boundary.
1223 if (LogAlign > 0)
1224 return false;
1225 R = N;
1226 return true;
1227 case ISD::BlockAddress:
1228 // Block address is always aligned at at least 4-byte boundary.
1229 if (LogAlign > 2 || !IsAligned(cast<BlockAddressSDNode>(N)->getOffset()))
1230 return false;
1231 R = N;
1232 return true;
1233 }
1234
1235 if (SelectGlobalAddress(N, R, false, LogAlign) ||
1236 SelectGlobalAddress(N, R, true, LogAlign))
1237 return true;
1238
1239 return false;
Colin LeMahieu51491352015-02-04 22:36:28 +00001240}
1241
Colin LeMahieu987b0942015-02-04 20:38:01 +00001242bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001243 bool UseGP, uint32_t LogAlign) {
1244 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001245 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001246 };
1247
Colin LeMahieu987b0942015-02-04 20:38:01 +00001248 switch (N.getOpcode()) {
1249 case ISD::ADD: {
1250 SDValue N0 = N.getOperand(0);
1251 SDValue N1 = N.getOperand(1);
1252 unsigned GAOpc = N0.getOpcode();
1253 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1254 return false;
1255 if (!UseGP && GAOpc != HexagonISD::CONST32)
1256 return false;
1257 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1258 SDValue Addr = N0.getOperand(0);
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001259 // For the purpose of alignment, sextvalue and zextvalue are the same.
1260 if (!IsAligned(Const->getZExtValue()))
1261 return false;
Colin LeMahieu987b0942015-02-04 20:38:01 +00001262 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1263 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1264 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1265 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1266 N.getValueType(), NewOff);
1267 return true;
1268 }
1269 }
1270 }
1271 break;
1272 }
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001273 case HexagonISD::CP:
1274 case HexagonISD::JT:
Colin LeMahieu987b0942015-02-04 20:38:01 +00001275 case HexagonISD::CONST32:
1276 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1277 // want in the instruction.
1278 if (!UseGP)
1279 R = N.getOperand(0);
1280 return !UseGP;
1281 case HexagonISD::CONST32_GP:
1282 if (UseGP)
1283 R = N.getOperand(0);
1284 return UseGP;
1285 default:
1286 return false;
1287 }
1288
1289 return false;
1290}
1291
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001292bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1293 // This (complex pattern) function is meant to detect a sign-extension
1294 // i32->i64 on a per-operand basis. This would allow writing single
1295 // patterns that would cover a number of combinations of different ways
1296 // a sign-extensions could be written. For example:
1297 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1298 // could match either one of these:
1299 // (mul (sext x) (sext_inreg y))
1300 // (mul (sext-load *p) (sext_inreg y))
1301 // (mul (sext_inreg x) (sext y))
1302 // etc.
1303 //
1304 // The returned value will have type i64 and its low word will
1305 // contain the value being extended. The high bits are not specified.
1306 // The returned type is i64 because the original type of N was i64,
1307 // but the users of this function should only use the low-word of the
1308 // result, e.g.
1309 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1310
1311 if (N.getValueType() != MVT::i64)
1312 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001313 unsigned Opc = N.getOpcode();
1314 switch (Opc) {
1315 case ISD::SIGN_EXTEND:
1316 case ISD::SIGN_EXTEND_INREG: {
1317 // sext_inreg has the source type as a separate operand.
1318 EVT T = Opc == ISD::SIGN_EXTEND
1319 ? N.getOperand(0).getValueType()
1320 : cast<VTSDNode>(N.getOperand(1))->getVT();
1321 if (T.getSizeInBits() != 32)
1322 return false;
1323 R = N.getOperand(0);
1324 break;
1325 }
1326 case ISD::LOAD: {
1327 LoadSDNode *L = cast<LoadSDNode>(N);
1328 if (L->getExtensionType() != ISD::SEXTLOAD)
1329 return false;
1330 // All extending loads extend to i32, so even if the value in
1331 // memory is shorter than 32 bits, it will be i32 after the load.
1332 if (L->getMemoryVT().getSizeInBits() > 32)
1333 return false;
1334 R = N;
1335 break;
1336 }
1337 default:
1338 return false;
1339 }
1340 EVT RT = R.getValueType();
1341 if (RT == MVT::i64)
1342 return true;
1343 assert(RT == MVT::i32);
1344 // This is only to produce a value of type i64. Do not rely on the
1345 // high bits produced by this.
1346 const SDLoc &dl(N);
1347 SDValue Ops[] = {
1348 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1349 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1350 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1351 };
1352 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1353 MVT::i64, Ops);
1354 R = SDValue(T, 0);
1355 return true;
1356}
1357
1358bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1359 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001360 unsigned Opc = Val.getOpcode();
1361 switch (Opc) {
1362 case ISD::SIGN_EXTEND:
1363 case ISD::ZERO_EXTEND:
1364 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001365 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001366 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001367 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001368 Src = Op0;
1369 return true;
1370 }
1371 break;
1372 }
1373 case ISD::SIGN_EXTEND_INREG:
1374 case ISD::AssertSext:
1375 case ISD::AssertZext:
1376 if (Val.getOperand(0).getValueType().isInteger()) {
1377 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001378 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001379 Src = Val.getOperand(0);
1380 return true;
1381 }
1382 }
1383 break;
1384 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001385 // Check if this is an AND with NumBits of lower bits set to 1.
1386 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001387 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001388 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001389 Src = Val.getOperand(1);
1390 return true;
1391 }
1392 }
1393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001394 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001395 Src = Val.getOperand(0);
1396 return true;
1397 }
1398 }
1399 break;
1400 }
1401 case ISD::OR:
1402 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001403 // OR/XOR with the lower NumBits bits set to 0.
1404 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001406 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001407 Src = Val.getOperand(1);
1408 return true;
1409 }
1410 }
1411 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001412 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001413 Src = Val.getOperand(0);
1414 return true;
1415 }
1416 }
1417 }
1418 default:
1419 break;
1420 }
1421 return false;
1422}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001423
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001424
Krzysztof Parzyszekb16a4e52016-11-14 20:53:09 +00001425bool HexagonDAGToDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001426 assert(N->getOpcode() == ISD::OR);
1427 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001428 if (!C)
1429 return false;
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001430
1431 // Detect when "or" is used to add an offset to a stack object.
1432 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
Matthias Braun941a7052016-07-28 18:40:00 +00001433 MachineFrameInfo &MFI = MF->getFrameInfo();
1434 unsigned A = MFI.getObjectAlignment(FN->getIndex());
Krzysztof Parzyszekbba0bf72016-07-15 15:35:52 +00001435 assert(isPowerOf2_32(A));
1436 int32_t Off = C->getSExtValue();
1437 // If the alleged offset fits in the zero bits guaranteed by
1438 // the alignment, then this or is really an add.
1439 return (Off >= 0) && (((A-1) & Off) == unsigned(Off));
1440 }
1441 return false;
1442}
1443
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001444bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1445 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1446}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001447
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001448bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1449 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1450 switch (N->getMemoryVT().getStoreSize()) {
1451 case 1:
1452 return StackSize <= 56; // 1*2^6 - 8
1453 case 2:
1454 return StackSize <= 120; // 2*2^6 - 8
1455 case 4:
1456 return StackSize <= 248; // 4*2^6 - 8
1457 default:
1458 return false;
1459 }
1460}
1461
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001462// Return true when the given node fits in a positive half word.
1463bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1464 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1465 int64_t V = CN->getSExtValue();
1466 return V > 0 && isInt<16>(V);
1467 }
1468 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1469 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1470 return VN->getVT().getSizeInBits() <= 16;
1471 }
1472 return false;
1473}
1474
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001475bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1476 return !CheckSingleUse || N->hasOneUse();
1477}
1478
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001479////////////////////////////////////////////////////////////////////////////////
1480// Rebalancing of address calculation trees
1481
1482static bool isOpcodeHandled(const SDNode *N) {
1483 switch (N->getOpcode()) {
1484 case ISD::ADD:
1485 case ISD::MUL:
1486 return true;
1487 case ISD::SHL:
1488 // We only handle constant shifts because these can be easily flattened
1489 // into multiplications by 2^Op1.
1490 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1491 default:
1492 return false;
1493 }
1494}
1495
1496/// \brief Return the weight of an SDNode
1497int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1498 if (!isOpcodeHandled(N))
1499 return 1;
1500 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1501 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1502 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1503 return RootWeights[N];
1504}
1505
1506int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1507 if (!isOpcodeHandled(N))
1508 return 0;
1509 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1510 "Cannot query height of unvisited/RAUW'd node!");
1511 return RootHeights[N];
1512}
1513
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001514namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001515struct WeightedLeaf {
1516 SDValue Value;
1517 int Weight;
1518 int InsertionOrder;
1519
1520 WeightedLeaf() : Value(SDValue()) { }
1521
1522 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1523 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1524 assert(Weight >= 0 && "Weight must be >= 0");
1525 }
1526
1527 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1528 assert(A.Value.getNode() && B.Value.getNode());
1529 return A.Weight == B.Weight ?
1530 (A.InsertionOrder > B.InsertionOrder) :
1531 (A.Weight > B.Weight);
1532 }
1533};
1534
1535/// A specialized priority queue for WeigthedLeaves. It automatically folds
1536/// constants and allows removal of non-top elements while maintaining the
1537/// priority order.
1538class LeafPrioQueue {
1539 SmallVector<WeightedLeaf, 8> Q;
1540 bool HaveConst;
1541 WeightedLeaf ConstElt;
1542 unsigned Opcode;
1543
1544public:
1545 bool empty() {
1546 return (!HaveConst && Q.empty());
1547 }
1548
1549 size_t size() {
1550 return Q.size() + HaveConst;
1551 }
1552
1553 bool hasConst() {
1554 return HaveConst;
1555 }
1556
1557 const WeightedLeaf &top() {
1558 if (HaveConst)
1559 return ConstElt;
1560 return Q.front();
1561 }
1562
1563 WeightedLeaf pop() {
1564 if (HaveConst) {
1565 HaveConst = false;
1566 return ConstElt;
1567 }
1568 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1569 return Q.pop_back_val();
1570 }
1571
1572 void push(WeightedLeaf L, bool SeparateConst=true) {
1573 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1574 if (Opcode == ISD::MUL &&
1575 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1576 return;
1577 if (Opcode == ISD::ADD &&
1578 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1579 return;
1580
1581 HaveConst = true;
1582 ConstElt = L;
1583 } else {
1584 Q.push_back(L);
1585 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1586 }
1587 }
1588
1589 /// Push L to the bottom of the queue regardless of its weight. If L is
1590 /// constant, it will not be folded with other constants in the queue.
1591 void pushToBottom(WeightedLeaf L) {
1592 L.Weight = 1000;
1593 push(L, false);
1594 }
1595
1596 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1597 /// lowest weight and remove it from the queue.
1598 WeightedLeaf findSHL(uint64_t MaxAmount);
1599
1600 WeightedLeaf findMULbyConst();
1601
1602 LeafPrioQueue(unsigned Opcode) :
1603 HaveConst(false), Opcode(Opcode) { }
1604};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001605} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001606
1607WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1608 int ResultPos;
1609 WeightedLeaf Result;
1610
1611 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1612 const WeightedLeaf &L = Q[Pos];
1613 const SDValue &Val = L.Value;
1614 if (Val.getOpcode() != ISD::SHL ||
1615 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1616 Val.getConstantOperandVal(1) > MaxAmount)
1617 continue;
1618 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1619 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1620 {
1621 Result = L;
1622 ResultPos = Pos;
1623 }
1624 }
1625
1626 if (Result.Value.getNode()) {
1627 Q.erase(&Q[ResultPos]);
1628 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1629 }
1630
1631 return Result;
1632}
1633
1634WeightedLeaf LeafPrioQueue::findMULbyConst() {
1635 int ResultPos;
1636 WeightedLeaf Result;
1637
1638 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1639 const WeightedLeaf &L = Q[Pos];
1640 const SDValue &Val = L.Value;
1641 if (Val.getOpcode() != ISD::MUL ||
1642 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1643 Val.getConstantOperandVal(1) > 127)
1644 continue;
1645 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1646 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1647 {
1648 Result = L;
1649 ResultPos = Pos;
1650 }
1651 }
1652
1653 if (Result.Value.getNode()) {
1654 Q.erase(&Q[ResultPos]);
1655 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1656 }
1657
1658 return Result;
1659}
1660
1661SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001662 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001663 return CurDAG->getConstant(MulFactor, SDLoc(N),
1664 N->getOperand(1).getValueType());
1665}
1666
1667/// @returns the value x for which 2^x is a factor of Val
1668static unsigned getPowerOf2Factor(SDValue Val) {
1669 if (Val.getOpcode() == ISD::MUL) {
1670 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001671 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1673 if (!C)
1674 continue;
1675 const APInt &CInt = C->getAPIntValue();
1676 if (CInt.getBoolValue())
1677 MaxFactor = CInt.countTrailingZeros();
1678 }
1679 return MaxFactor;
1680 }
1681 if (Val.getOpcode() == ISD::SHL) {
1682 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1683 return 0;
1684 return (unsigned) Val.getConstantOperandVal(1);
1685 }
1686
1687 return 0;
1688}
1689
1690/// @returns true if V>>Amount will eliminate V's operation on its child
1691static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1692 if (V.getOpcode() == ISD::MUL) {
1693 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001694 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001695 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001696 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001697 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1698 return (NewConst == 1);
1699 }
1700 } else if (V.getOpcode() == ISD::SHL) {
1701 return (Amount == V.getConstantOperandVal(1));
1702 }
1703
1704 return false;
1705}
1706
1707SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1708 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1709 if (V.getOpcode() == ISD::MUL) {
1710 for (int i=0; i < 2; ++i) {
1711 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1712 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1713 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1714 if (NewConst == 1)
1715 return Ops[!i];
1716 Ops[i] = CurDAG->getConstant(NewConst,
1717 SDLoc(V), V.getValueType());
1718 break;
1719 }
1720 }
1721 } else if (V.getOpcode() == ISD::SHL) {
1722 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1723 if (ShiftAmount == Power)
1724 return Ops[0];
1725 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1726 SDLoc(V), V.getValueType());
1727 }
1728
1729 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1730}
1731
1732static bool isTargetConstant(const SDValue &V) {
1733 return V.getOpcode() == HexagonISD::CONST32 ||
1734 V.getOpcode() == HexagonISD::CONST32_GP;
1735}
1736
1737unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1738 if (GAUsesInFunction.count(V))
1739 return GAUsesInFunction[V];
1740
1741 unsigned Result = 0;
1742 const Function *CurF = CurDAG->getMachineFunction().getFunction();
1743 for (const User *U : V->users()) {
1744 if (isa<Instruction>(U) &&
1745 cast<Instruction>(U)->getParent()->getParent() == CurF)
1746 ++Result;
1747 }
1748
1749 GAUsesInFunction[V] = Result;
1750
1751 return Result;
1752}
1753
1754/// Note - After calling this, N may be dead. It may have been replaced by a
1755/// new node, so always use the returned value in place of N.
1756///
1757/// @returns The SDValue taking the place of N (which could be N if it is
1758/// unchanged)
1759SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1760 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1761 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1762 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1763
1764 // Return early if this node was already visited
1765 if (RootWeights[N] != -1)
1766 return SDValue(N, 0);
1767
1768 assert(isOpcodeHandled(N));
1769
1770 SDValue Op0 = N->getOperand(0);
1771 SDValue Op1 = N->getOperand(1);
1772
1773 // Return early if the operands will remain unchanged or are all roots
1774 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1775 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1776 SDNode *Op0N = Op0.getNode();
1777 int Weight;
1778 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1779 Weight = getWeight(balanceSubTree(Op0N).getNode());
1780 // Weight = calculateWeight(Op0N);
1781 } else
1782 Weight = getWeight(Op0N);
1783
1784 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1785 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1786 Weight += getWeight(balanceSubTree(Op1N).getNode());
1787 // Weight += calculateWeight(Op1N);
1788 } else
1789 Weight += getWeight(Op1N);
1790
1791 RootWeights[N] = Weight;
1792 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1793 getHeight(N->getOperand(1).getNode())) + 1;
1794
1795 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1796 << " Height=" << RootHeights[N] << "): ");
1797 DEBUG(N->dump());
1798
1799 return SDValue(N, 0);
1800 }
1801
1802 DEBUG(dbgs() << "** Balancing root node: ");
1803 DEBUG(N->dump());
1804
1805 unsigned NOpcode = N->getOpcode();
1806
1807 LeafPrioQueue Leaves(NOpcode);
1808 SmallVector<SDValue, 4> Worklist;
1809 Worklist.push_back(SDValue(N, 0));
1810
1811 // SHL nodes will be converted to MUL nodes
1812 if (NOpcode == ISD::SHL)
1813 NOpcode = ISD::MUL;
1814
1815 bool CanFactorize = false;
1816 WeightedLeaf Mul1, Mul2;
1817 unsigned MaxPowerOf2 = 0;
1818 WeightedLeaf GA;
1819
1820 // Do not try to factor out a shift if there is already a shift at the tip of
1821 // the tree.
1822 bool HaveTopLevelShift = false;
1823 if (TopLevel &&
1824 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1825 Op0.getConstantOperandVal(1) < 4) ||
1826 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1827 Op1.getConstantOperandVal(1) < 4)))
1828 HaveTopLevelShift = true;
1829
1830 // Flatten the subtree into an ordered list of leaves; at the same time
1831 // determine whether the tree is already balanced.
1832 int InsertionOrder = 0;
1833 SmallDenseMap<SDValue, int> NodeHeights;
1834 bool Imbalanced = false;
1835 int CurrentWeight = 0;
1836 while (!Worklist.empty()) {
1837 SDValue Child = Worklist.pop_back_val();
1838
1839 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1840 // CASE 1: Child is a root note
1841
1842 int Weight = RootWeights[Child.getNode()];
1843 if (Weight == -1) {
1844 Child = balanceSubTree(Child.getNode());
1845 // calculateWeight(Child.getNode());
1846 Weight = getWeight(Child.getNode());
1847 } else if (Weight == -2) {
1848 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1849 // made. Our worklist isn't up to date anymore.
1850 // Restart the whole process.
1851 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1852 return balanceSubTree(N, TopLevel);
1853 }
1854
1855 NodeHeights[Child] = 1;
1856 CurrentWeight += Weight;
1857
1858 unsigned PowerOf2;
1859 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1860 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1861 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1862 // Try to identify two factorizable MUL/SHL children greedily. Leave
1863 // them out of the priority queue for now so we can deal with them
1864 // after.
1865 if (!Mul1.Value.getNode()) {
1866 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1867 MaxPowerOf2 = PowerOf2;
1868 } else {
1869 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1870 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1871
1872 // Our addressing modes can only shift by a maximum of 3
1873 if (MaxPowerOf2 > 3)
1874 MaxPowerOf2 = 3;
1875
1876 CanFactorize = true;
1877 }
1878 } else
1879 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1880 } else if (!isOpcodeHandled(Child.getNode())) {
1881 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1882 int Weight = getWeight(Child.getNode());
1883
1884 NodeHeights[Child] = getHeight(Child.getNode());
1885 CurrentWeight += Weight;
1886
1887 if (isTargetConstant(Child) && !GA.Value.getNode())
1888 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1889 else
1890 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1891 } else {
1892 // CASE 3: Child is a subtree of same opcode
1893 // Visit children first, then flatten.
1894 unsigned ChildOpcode = Child.getOpcode();
1895 assert(ChildOpcode == NOpcode ||
1896 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1897
1898 // Convert SHL to MUL
1899 SDValue Op1;
1900 if (ChildOpcode == ISD::SHL)
1901 Op1 = getMultiplierForSHL(Child.getNode());
1902 else
1903 Op1 = Child->getOperand(1);
1904
1905 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
1906 assert(!NodeHeights.count(Child) && "Parent visited before children?");
1907 // Visit children first, then re-visit this node
1908 Worklist.push_back(Child);
1909 Worklist.push_back(Op1);
1910 Worklist.push_back(Child->getOperand(0));
1911 } else {
1912 // Back at this node after visiting the children
1913 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
1914 Imbalanced = true;
1915
1916 NodeHeights[Child] = std::max(NodeHeights[Op1],
1917 NodeHeights[Child->getOperand(0)]) + 1;
1918 }
1919 }
1920 }
1921
1922 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
1923 << " weight=" << CurrentWeight << " imbalanced="
1924 << Imbalanced << "\n");
1925
1926 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
1927 // This factors out a shift in order to match memw(a<<Y+b).
1928 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
1929 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
1930 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
1931 int Weight = Mul1.Weight + Mul2.Weight;
1932 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
1933 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
1934 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
1935 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
1936 Mul1Factored, Mul2Factored);
1937 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
1938 Mul1.Value.getValueType());
1939 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
1940 Sum, Const);
1941 NodeHeights[New] = Height;
1942 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
1943 } else if (Mul1.Value.getNode()) {
1944 // We failed to factorize two MULs, so now the Muls are left outside the
1945 // queue... add them back.
1946 Leaves.push(Mul1);
1947 if (Mul2.Value.getNode())
1948 Leaves.push(Mul2);
1949 CanFactorize = false;
1950 }
1951
1952 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
1953 // and the root node itself is not used more than twice. This reduces the
1954 // amount of additional constant extenders introduced by this optimization.
1955 bool CombinedGA = false;
1956 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
1957 GA.Value.hasOneUse() && N->use_size() < 3) {
1958 GlobalAddressSDNode *GANode =
1959 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
1960 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
1961
1962 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
1963 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
1964 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
1965 << "): ");
1966 DEBUG(GANode->dump());
1967
1968 SDValue NewTGA =
1969 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
1970 GANode->getValueType(0),
1971 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
1972 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
1973 GA.Value.getValueType(), NewTGA);
1974 GA.Weight += Leaves.top().Weight;
1975
1976 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
1977 CombinedGA = true;
1978
1979 Leaves.pop(); // Remove the offset constant from the queue
1980 }
1981 }
1982
1983 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
1984 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
1985 RootWeights[N] = CurrentWeight;
1986 RootHeights[N] = NodeHeights[SDValue(N, 0)];
1987
1988 return SDValue(N, 0);
1989 }
1990
1991 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
1992 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
1993 WeightedLeaf SHL = Leaves.findSHL(31);
1994 if (SHL.Value.getNode()) {
1995 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
1996 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
1997 GA.Value.getValueType(),
1998 GA.Value, SHL.Value);
1999 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2000 NodeHeights[GA.Value] = Height;
2001 }
2002 }
2003
2004 if (GA.Value.getNode())
2005 Leaves.push(GA);
2006
2007 // If this is the top level and we haven't factored out a shift, we should try
2008 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2009 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2010 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2011 Leaves.pushToBottom(Leaves.pop());
2012 }
2013
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002014 const DataLayout &DL = CurDAG->getDataLayout();
2015 const TargetLowering &TLI = *getTargetLowering();
2016
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002017 // Rebuild the tree using Huffman's algorithm
2018 while (Leaves.size() > 1) {
2019 WeightedLeaf L0 = Leaves.pop();
2020
2021 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2022 // otherwise just get the next leaf
2023 WeightedLeaf L1 = Leaves.findMULbyConst();
2024 if (!L1.Value.getNode())
2025 L1 = Leaves.pop();
2026
2027 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2028
2029 SDValue V0 = L0.Value;
2030 int V0Weight = L0.Weight;
2031 SDValue V1 = L1.Value;
2032 int V1Weight = L1.Weight;
2033
2034 // Make sure that none of these nodes have been RAUW'd
2035 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2036 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2037 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2038 return balanceSubTree(N, TopLevel);
2039 }
2040
2041 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2042 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2043 EVT VT = N->getValueType(0);
2044 SDValue NewNode;
2045
2046 if (V0C && !V1C) {
2047 std::swap(V0, V1);
2048 std::swap(V0C, V1C);
2049 }
2050
2051 // Calculate height of this node
2052 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2053 "Children must have been visited before re-combining them!");
2054 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2055
2056 // Rebuild this node (and restore SHL from MUL if needed)
2057 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2058 NewNode = CurDAG->getNode(
2059 ISD::SHL, SDLoc(V0), VT, V0,
2060 CurDAG->getConstant(
2061 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002062 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002063 else
2064 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2065
2066 NodeHeights[NewNode] = Height;
2067
2068 int Weight = V0Weight + V1Weight;
2069 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2070
2071 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2072 << Height << "):\n");
2073 DEBUG(NewNode.dump());
2074 }
2075
2076 assert(Leaves.size() == 1);
2077 SDValue NewRoot = Leaves.top().Value;
2078
2079 assert(NodeHeights.count(NewRoot));
2080 int Height = NodeHeights[NewRoot];
2081
2082 // Restore SHL if we earlier converted it to a MUL
2083 if (NewRoot.getOpcode() == ISD::MUL) {
2084 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2085 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2086 EVT VT = NewRoot.getValueType();
2087 SDValue V0 = NewRoot.getOperand(0);
2088 NewRoot = CurDAG->getNode(
2089 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002090 CurDAG->getConstant(
2091 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2092 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002093 }
2094 }
2095
2096 if (N != NewRoot.getNode()) {
2097 DEBUG(dbgs() << "--> Root is now: ");
2098 DEBUG(NewRoot.dump());
2099
2100 // Replace all uses of old root by new root
2101 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2102 // Mark that we have RAUW'd N
2103 RootWeights[N] = -2;
2104 } else {
2105 DEBUG(dbgs() << "--> Root unchanged.\n");
2106 }
2107
2108 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2109 RootHeights[NewRoot.getNode()] = Height;
2110
2111 return NewRoot;
2112}
2113
2114void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002115 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002116 SDNode *N = &*I++;
2117 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2118 continue;
2119
2120 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2121 if (BasePtr.getOpcode() != ISD::ADD)
2122 continue;
2123
2124 // We've already processed this node
2125 if (RootWeights.count(BasePtr.getNode()))
2126 continue;
2127
2128 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2129 DEBUG(N->dump());
2130
2131 // FindRoots
2132 SmallVector<SDNode *, 4> Worklist;
2133
2134 Worklist.push_back(BasePtr.getOperand(0).getNode());
2135 Worklist.push_back(BasePtr.getOperand(1).getNode());
2136
2137 while (!Worklist.empty()) {
2138 SDNode *N = Worklist.pop_back_val();
2139 unsigned Opcode = N->getOpcode();
2140
2141 if (!isOpcodeHandled(N))
2142 continue;
2143
2144 Worklist.push_back(N->getOperand(0).getNode());
2145 Worklist.push_back(N->getOperand(1).getNode());
2146
2147 // Not a root if it has only one use and same opcode as its parent
2148 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2149 continue;
2150
2151 // This root node has already been processed
2152 if (RootWeights.count(N))
2153 continue;
2154
2155 RootWeights[N] = -1;
2156 }
2157
2158 // Balance node itself
2159 RootWeights[BasePtr.getNode()] = -1;
2160 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2161
2162 if (N->getOpcode() == ISD::LOAD)
2163 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2164 NewBasePtr, N->getOperand(2));
2165 else
2166 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2167 NewBasePtr, N->getOperand(3));
2168
2169 DEBUG(dbgs() << "--> Final node: ");
2170 DEBUG(N->dump());
2171 }
2172
2173 CurDAG->RemoveDeadNodes();
2174 GAUsesInFunction.clear();
2175 RootHeights.clear();
2176 RootWeights.clear();
2177}
2178