blob: 3618bbc938cf5e17f96c929e855e053ed20e95c8 [file] [log] [blame]
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001//===-- HexagonISelDAGToDAGHVX.cpp ----------------------------------------===//
2//
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#include "Hexagon.h"
11#include "HexagonISelDAGToDAG.h"
12#include "HexagonISelLowering.h"
13#include "HexagonTargetMachine.h"
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +000014#include "llvm/ADT/SetVector.h"
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +000015#include "llvm/CodeGen/MachineInstrBuilder.h"
16#include "llvm/CodeGen/SelectionDAGISel.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Debug.h"
20
21#include <deque>
22#include <map>
23#include <set>
24#include <utility>
25#include <vector>
26
27#define DEBUG_TYPE "hexagon-isel"
28
29using namespace llvm;
30
Benjamin Kramer802e6252017-12-24 12:46:22 +000031namespace {
32
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +000033// --------------------------------------------------------------------
34// Implementation of permutation networks.
35
36// Implementation of the node routing through butterfly networks:
37// - Forward delta.
38// - Reverse delta.
39// - Benes.
40//
41//
42// Forward delta network consists of log(N) steps, where N is the number
43// of inputs. In each step, an input can stay in place, or it can get
44// routed to another position[1]. The step after that consists of two
45// networks, each half in size in terms of the number of nodes. In those
46// terms, in the given step, an input can go to either the upper or the
47// lower network in the next step.
48//
49// [1] Hexagon's vdelta/vrdelta allow an element to be routed to both
50// positions as long as there is no conflict.
51
52// Here's a delta network for 8 inputs, only the switching routes are
53// shown:
54//
55// Steps:
56// |- 1 ---------------|- 2 -----|- 3 -|
57//
58// Inp[0] *** *** *** *** Out[0]
59// \ / \ / \ /
60// \ / \ / X
61// \ / \ / / \
62// Inp[1] *** \ / *** X *** *** Out[1]
63// \ \ / / \ / \ /
64// \ \ / / X X
65// \ \ / / / \ / \
66// Inp[2] *** \ \ / / *** X *** *** Out[2]
67// \ \ X / / / \ \ /
68// \ \ / \ / / / \ X
69// \ X X / / \ / \
70// Inp[3] *** \ / \ / \ / *** *** *** Out[3]
71// \ X X X /
72// \ / \ / \ / \ /
73// X X X X
74// / \ / \ / \ / \
75// / X X X \
76// Inp[4] *** / \ / \ / \ *** *** *** Out[4]
77// / X X \ \ / \ /
78// / / \ / \ \ \ / X
79// / / X \ \ \ / / \
80// Inp[5] *** / / \ \ *** X *** *** Out[5]
81// / / \ \ \ / \ /
82// / / \ \ X X
83// / / \ \ / \ / \
84// Inp[6] *** / \ *** X *** *** Out[6]
85// / \ / \ \ /
86// / \ / \ X
87// / \ / \ / \
88// Inp[7] *** *** *** *** Out[7]
89//
90//
91// Reverse delta network is same as delta network, with the steps in
92// the opposite order.
93//
94//
95// Benes network is a forward delta network immediately followed by
96// a reverse delta network.
97
98
99// Graph coloring utility used to partition nodes into two groups:
100// they will correspond to nodes routed to the upper and lower networks.
101struct Coloring {
102 enum : uint8_t {
103 None = 0,
104 Red,
105 Black
106 };
107
108 using Node = int;
109 using MapType = std::map<Node,uint8_t>;
110 static constexpr Node Ignore = Node(-1);
111
112 Coloring(ArrayRef<Node> Ord) : Order(Ord) {
113 build();
114 if (!color())
115 Colors.clear();
116 }
117
118 const MapType &colors() const {
119 return Colors;
120 }
121
122 uint8_t other(uint8_t Color) {
123 if (Color == None)
124 return Red;
125 return Color == Red ? Black : Red;
126 }
127
128 void dump() const;
129
130private:
131 ArrayRef<Node> Order;
132 MapType Colors;
133 std::set<Node> Needed;
134
135 using NodeSet = std::set<Node>;
136 std::map<Node,NodeSet> Edges;
137
138 Node conj(Node Pos) {
139 Node Num = Order.size();
140 return (Pos < Num/2) ? Pos + Num/2 : Pos - Num/2;
141 }
142
143 uint8_t getColor(Node N) {
144 auto F = Colors.find(N);
Simon Pilgrima335e1e2017-12-09 16:19:18 +0000145 return F != Colors.end() ? F->second : (uint8_t)None;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000146 }
147
148 std::pair<bool,uint8_t> getUniqueColor(const NodeSet &Nodes);
149
150 void build();
151 bool color();
152};
Benjamin Kramer802e6252017-12-24 12:46:22 +0000153} // namespace
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000154
155std::pair<bool,uint8_t> Coloring::getUniqueColor(const NodeSet &Nodes) {
156 uint8_t Color = None;
157 for (Node N : Nodes) {
158 uint8_t ColorN = getColor(N);
159 if (ColorN == None)
160 continue;
161 if (Color == None)
162 Color = ColorN;
163 else if (Color != None && Color != ColorN)
164 return { false, None };
165 }
166 return { true, Color };
167}
168
169void Coloring::build() {
170 // Add Order[P] and Order[conj(P)] to Edges.
171 for (unsigned P = 0; P != Order.size(); ++P) {
172 Node I = Order[P];
173 if (I != Ignore) {
174 Needed.insert(I);
175 Node PC = Order[conj(P)];
176 if (PC != Ignore && PC != I)
177 Edges[I].insert(PC);
178 }
179 }
180 // Add I and conj(I) to Edges.
181 for (unsigned I = 0; I != Order.size(); ++I) {
182 if (!Needed.count(I))
183 continue;
184 Node C = conj(I);
185 // This will create an entry in the edge table, even if I is not
186 // connected to any other node. This is necessary, because it still
187 // needs to be colored.
188 NodeSet &Is = Edges[I];
189 if (Needed.count(C))
190 Is.insert(C);
191 }
192}
193
194bool Coloring::color() {
195 SetVector<Node> FirstQ;
196 auto Enqueue = [this,&FirstQ] (Node N) {
197 SetVector<Node> Q;
198 Q.insert(N);
199 for (unsigned I = 0; I != Q.size(); ++I) {
200 NodeSet &Ns = Edges[Q[I]];
201 Q.insert(Ns.begin(), Ns.end());
202 }
203 FirstQ.insert(Q.begin(), Q.end());
204 };
205 for (Node N : Needed)
206 Enqueue(N);
207
208 for (Node N : FirstQ) {
209 if (Colors.count(N))
210 continue;
211 NodeSet &Ns = Edges[N];
212 auto P = getUniqueColor(Ns);
213 if (!P.first)
214 return false;
215 Colors[N] = other(P.second);
216 }
217
218 // First, color nodes that don't have any dups.
219 for (auto E : Edges) {
220 Node N = E.first;
221 if (!Needed.count(conj(N)) || Colors.count(N))
222 continue;
223 auto P = getUniqueColor(E.second);
224 if (!P.first)
225 return false;
226 Colors[N] = other(P.second);
227 }
228
229 // Now, nodes that are still uncolored. Since the graph can be modified
230 // in this step, create a work queue.
231 std::vector<Node> WorkQ;
232 for (auto E : Edges) {
233 Node N = E.first;
234 if (!Colors.count(N))
235 WorkQ.push_back(N);
236 }
237
238 for (unsigned I = 0; I < WorkQ.size(); ++I) {
239 Node N = WorkQ[I];
240 NodeSet &Ns = Edges[N];
241 auto P = getUniqueColor(Ns);
242 if (P.first) {
243 Colors[N] = other(P.second);
244 continue;
245 }
246
247 // Coloring failed. Split this node.
248 Node C = conj(N);
249 uint8_t ColorN = other(None);
250 uint8_t ColorC = other(ColorN);
251 NodeSet &Cs = Edges[C];
252 NodeSet CopyNs = Ns;
253 for (Node M : CopyNs) {
254 uint8_t ColorM = getColor(M);
255 if (ColorM == ColorC) {
256 // Connect M with C, disconnect M from N.
257 Cs.insert(M);
258 Edges[M].insert(C);
259 Ns.erase(M);
260 Edges[M].erase(N);
261 }
262 }
263 Colors[N] = ColorN;
264 Colors[C] = ColorC;
265 }
266
267 // Explicitly assign "None" all all uncolored nodes.
268 for (unsigned I = 0; I != Order.size(); ++I)
269 if (Colors.count(I) == 0)
270 Colors[I] = None;
271
272 return true;
273}
274
275LLVM_DUMP_METHOD
276void Coloring::dump() const {
277 dbgs() << "{ Order: {";
278 for (unsigned I = 0; I != Order.size(); ++I) {
279 Node P = Order[I];
280 if (P != Ignore)
281 dbgs() << ' ' << P;
282 else
283 dbgs() << " -";
284 }
285 dbgs() << " }\n";
286 dbgs() << " Needed: {";
287 for (Node N : Needed)
288 dbgs() << ' ' << N;
289 dbgs() << " }\n";
290
291 dbgs() << " Edges: {\n";
292 for (auto E : Edges) {
293 dbgs() << " " << E.first << " -> {";
294 for (auto N : E.second)
295 dbgs() << ' ' << N;
296 dbgs() << " }\n";
297 }
298 dbgs() << " }\n";
299
300 static const char *const Names[] = { "None", "Red", "Black" };
301 dbgs() << " Colors: {\n";
302 for (auto C : Colors)
303 dbgs() << " " << C.first << " -> " << Names[C.second] << "\n";
304 dbgs() << " }\n}\n";
305}
306
Benjamin Kramer802e6252017-12-24 12:46:22 +0000307namespace {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000308// Base class of for reordering networks. They don't strictly need to be
309// permutations, as outputs with repeated occurrences of an input element
310// are allowed.
311struct PermNetwork {
312 using Controls = std::vector<uint8_t>;
313 using ElemType = int;
314 static constexpr ElemType Ignore = ElemType(-1);
315
316 enum : uint8_t {
317 None,
318 Pass,
319 Switch
320 };
321 enum : uint8_t {
322 Forward,
323 Reverse
324 };
325
326 PermNetwork(ArrayRef<ElemType> Ord, unsigned Mult = 1) {
327 Order.assign(Ord.data(), Ord.data()+Ord.size());
328 Log = 0;
329
330 unsigned S = Order.size();
331 while (S >>= 1)
332 ++Log;
333
334 Table.resize(Order.size());
335 for (RowType &Row : Table)
336 Row.resize(Mult*Log, None);
337 }
338
339 void getControls(Controls &V, unsigned StartAt, uint8_t Dir) const {
340 unsigned Size = Order.size();
341 V.resize(Size);
342 for (unsigned I = 0; I != Size; ++I) {
343 unsigned W = 0;
344 for (unsigned L = 0; L != Log; ++L) {
345 unsigned C = ctl(I, StartAt+L) == Switch;
346 if (Dir == Forward)
347 W |= C << (Log-1-L);
348 else
349 W |= C << L;
350 }
351 assert(isUInt<8>(W));
352 V[I] = uint8_t(W);
353 }
354 }
355
356 uint8_t ctl(ElemType Pos, unsigned Step) const {
357 return Table[Pos][Step];
358 }
359 unsigned size() const {
360 return Order.size();
361 }
362 unsigned steps() const {
363 return Log;
364 }
365
366protected:
367 unsigned Log;
368 std::vector<ElemType> Order;
369 using RowType = std::vector<uint8_t>;
370 std::vector<RowType> Table;
371};
372
373struct ForwardDeltaNetwork : public PermNetwork {
374 ForwardDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
375
376 bool run(Controls &V) {
377 if (!route(Order.data(), Table.data(), size(), 0))
378 return false;
379 getControls(V, 0, Forward);
380 return true;
381 }
382
383private:
384 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
385};
386
387struct ReverseDeltaNetwork : public PermNetwork {
388 ReverseDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
389
390 bool run(Controls &V) {
391 if (!route(Order.data(), Table.data(), size(), 0))
392 return false;
393 getControls(V, 0, Reverse);
394 return true;
395 }
396
397private:
398 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
399};
400
401struct BenesNetwork : public PermNetwork {
402 BenesNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord, 2) {}
403
404 bool run(Controls &F, Controls &R) {
405 if (!route(Order.data(), Table.data(), size(), 0))
406 return false;
407
408 getControls(F, 0, Forward);
409 getControls(R, Log, Reverse);
410 return true;
411 }
412
413private:
414 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
415};
Benjamin Kramer802e6252017-12-24 12:46:22 +0000416} // namespace
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000417
418bool ForwardDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
419 unsigned Step) {
420 bool UseUp = false, UseDown = false;
421 ElemType Num = Size;
422
423 // Cannot use coloring here, because coloring is used to determine
424 // the "big" switch, i.e. the one that changes halves, and in a forward
425 // network, a color can be simultaneously routed to both halves in the
426 // step we're working on.
427 for (ElemType J = 0; J != Num; ++J) {
428 ElemType I = P[J];
429 // I is the position in the input,
430 // J is the position in the output.
431 if (I == Ignore)
432 continue;
433 uint8_t S;
434 if (I < Num/2)
435 S = (J < Num/2) ? Pass : Switch;
436 else
437 S = (J < Num/2) ? Switch : Pass;
438
439 // U is the element in the table that needs to be updated.
440 ElemType U = (S == Pass) ? I : (I < Num/2 ? I+Num/2 : I-Num/2);
441 if (U < Num/2)
442 UseUp = true;
443 else
444 UseDown = true;
445 if (T[U][Step] != S && T[U][Step] != None)
446 return false;
447 T[U][Step] = S;
448 }
449
450 for (ElemType J = 0; J != Num; ++J)
451 if (P[J] != Ignore && P[J] >= Num/2)
452 P[J] -= Num/2;
453
454 if (Step+1 < Log) {
455 if (UseUp && !route(P, T, Size/2, Step+1))
456 return false;
457 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
458 return false;
459 }
460 return true;
461}
462
463bool ReverseDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
464 unsigned Step) {
465 unsigned Pets = Log-1 - Step;
466 bool UseUp = false, UseDown = false;
467 ElemType Num = Size;
468
469 // In this step half-switching occurs, so coloring can be used.
470 Coloring G({P,Size});
471 const Coloring::MapType &M = G.colors();
472 if (M.empty())
473 return false;
474
475 uint8_t ColorUp = Coloring::None;
476 for (ElemType J = 0; J != Num; ++J) {
477 ElemType I = P[J];
478 // I is the position in the input,
479 // J is the position in the output.
480 if (I == Ignore)
481 continue;
482 uint8_t C = M.at(I);
483 if (C == Coloring::None)
484 continue;
485 // During "Step", inputs cannot switch halves, so if the "up" color
486 // is still unknown, make sure that it is selected in such a way that
487 // "I" will stay in the same half.
488 bool InpUp = I < Num/2;
489 if (ColorUp == Coloring::None)
490 ColorUp = InpUp ? C : G.other(C);
491 if ((C == ColorUp) != InpUp) {
492 // If I should go to a different half than where is it now, give up.
493 return false;
494 }
495
496 uint8_t S;
497 if (InpUp) {
498 S = (J < Num/2) ? Pass : Switch;
499 UseUp = true;
500 } else {
501 S = (J < Num/2) ? Switch : Pass;
502 UseDown = true;
503 }
504 T[J][Pets] = S;
505 }
506
507 // Reorder the working permutation according to the computed switch table
508 // for the last step (i.e. Pets).
Simon Pilgrim3d0be4f2017-12-09 16:04:57 +0000509 for (ElemType J = 0, E = Size / 2; J != E; ++J) {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000510 ElemType PJ = P[J]; // Current values of P[J]
511 ElemType PC = P[J+Size/2]; // and P[conj(J)]
512 ElemType QJ = PJ; // New values of P[J]
513 ElemType QC = PC; // and P[conj(J)]
514 if (T[J][Pets] == Switch)
515 QC = PJ;
516 if (T[J+Size/2][Pets] == Switch)
517 QJ = PC;
518 P[J] = QJ;
519 P[J+Size/2] = QC;
520 }
521
522 for (ElemType J = 0; J != Num; ++J)
523 if (P[J] != Ignore && P[J] >= Num/2)
524 P[J] -= Num/2;
525
526 if (Step+1 < Log) {
527 if (UseUp && !route(P, T, Size/2, Step+1))
528 return false;
529 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
530 return false;
531 }
532 return true;
533}
534
535bool BenesNetwork::route(ElemType *P, RowType *T, unsigned Size,
536 unsigned Step) {
537 Coloring G({P,Size});
538 const Coloring::MapType &M = G.colors();
539 if (M.empty())
540 return false;
541 ElemType Num = Size;
542
543 unsigned Pets = 2*Log-1 - Step;
544 bool UseUp = false, UseDown = false;
545
546 // Both assignments, i.e. Red->Up and Red->Down are valid, but they will
547 // result in different controls. Let's pick the one where the first
548 // control will be "Pass".
549 uint8_t ColorUp = Coloring::None;
550 for (ElemType J = 0; J != Num; ++J) {
551 ElemType I = P[J];
552 if (I == Ignore)
553 continue;
554 uint8_t C = M.at(I);
555 if (C == Coloring::None)
556 continue;
557 if (ColorUp == Coloring::None) {
558 ColorUp = (I < Num/2) ? Coloring::Red : Coloring::Black;
559 }
560 unsigned CI = (I < Num/2) ? I+Num/2 : I-Num/2;
561 if (C == ColorUp) {
562 if (I < Num/2)
563 T[I][Step] = Pass;
564 else
565 T[CI][Step] = Switch;
566 T[J][Pets] = (J < Num/2) ? Pass : Switch;
567 UseUp = true;
568 } else { // Down
569 if (I < Num/2)
570 T[CI][Step] = Switch;
571 else
572 T[I][Step] = Pass;
573 T[J][Pets] = (J < Num/2) ? Switch : Pass;
574 UseDown = true;
575 }
576 }
577
578 // Reorder the working permutation according to the computed switch table
579 // for the last step (i.e. Pets).
580 for (ElemType J = 0; J != Num/2; ++J) {
581 ElemType PJ = P[J]; // Current values of P[J]
582 ElemType PC = P[J+Num/2]; // and P[conj(J)]
583 ElemType QJ = PJ; // New values of P[J]
584 ElemType QC = PC; // and P[conj(J)]
585 if (T[J][Pets] == Switch)
586 QC = PJ;
587 if (T[J+Num/2][Pets] == Switch)
588 QJ = PC;
589 P[J] = QJ;
590 P[J+Num/2] = QC;
591 }
592
593 for (ElemType J = 0; J != Num; ++J)
594 if (P[J] != Ignore && P[J] >= Num/2)
595 P[J] -= Num/2;
596
597 if (Step+1 < Log) {
598 if (UseUp && !route(P, T, Size/2, Step+1))
599 return false;
600 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
601 return false;
602 }
603 return true;
604}
605
606// --------------------------------------------------------------------
607// Support for building selection results (output instructions that are
608// parts of the final selection).
609
Benjamin Kramer802e6252017-12-24 12:46:22 +0000610namespace {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000611struct OpRef {
612 OpRef(SDValue V) : OpV(V) {}
613 bool isValue() const { return OpV.getNode() != nullptr; }
614 bool isValid() const { return isValue() || !(OpN & Invalid); }
615 static OpRef res(int N) { return OpRef(Whole | (N & Index)); }
616 static OpRef fail() { return OpRef(Invalid); }
617
618 static OpRef lo(const OpRef &R) {
619 assert(!R.isValue());
620 return OpRef(R.OpN & (Undef | Index | LoHalf));
621 }
622 static OpRef hi(const OpRef &R) {
623 assert(!R.isValue());
624 return OpRef(R.OpN & (Undef | Index | HiHalf));
625 }
626 static OpRef undef(MVT Ty) { return OpRef(Undef | Ty.SimpleTy); }
627
628 // Direct value.
629 SDValue OpV = SDValue();
630
631 // Reference to the operand of the input node:
632 // If the 31st bit is 1, it's undef, otherwise, bits 28..0 are the
633 // operand index:
634 // If bit 30 is set, it's the high half of the operand.
635 // If bit 29 is set, it's the low half of the operand.
636 unsigned OpN = 0;
637
638 enum : unsigned {
639 Invalid = 0x10000000,
640 LoHalf = 0x20000000,
641 HiHalf = 0x40000000,
642 Whole = LoHalf | HiHalf,
643 Undef = 0x80000000,
644 Index = 0x0FFFFFFF, // Mask of the index value.
645 IndexBits = 28,
646 };
647
648 void print(raw_ostream &OS, const SelectionDAG &G) const;
649
650private:
651 OpRef(unsigned N) : OpN(N) {}
652};
653
654struct NodeTemplate {
655 NodeTemplate() = default;
656 unsigned Opc = 0;
657 MVT Ty = MVT::Other;
658 std::vector<OpRef> Ops;
659
660 void print(raw_ostream &OS, const SelectionDAG &G) const;
661};
662
663struct ResultStack {
664 ResultStack(SDNode *Inp)
665 : InpNode(Inp), InpTy(Inp->getValueType(0).getSimpleVT()) {}
666 SDNode *InpNode;
667 MVT InpTy;
668 unsigned push(const NodeTemplate &Res) {
669 List.push_back(Res);
670 return List.size()-1;
671 }
672 unsigned push(unsigned Opc, MVT Ty, std::vector<OpRef> &&Ops) {
673 NodeTemplate Res;
674 Res.Opc = Opc;
675 Res.Ty = Ty;
676 Res.Ops = Ops;
677 return push(Res);
678 }
679 bool empty() const { return List.empty(); }
680 unsigned size() const { return List.size(); }
681 unsigned top() const { return size()-1; }
682 const NodeTemplate &operator[](unsigned I) const { return List[I]; }
683 unsigned reset(unsigned NewTop) {
684 List.resize(NewTop+1);
685 return NewTop;
686 }
687
688 using BaseType = std::vector<NodeTemplate>;
689 BaseType::iterator begin() { return List.begin(); }
690 BaseType::iterator end() { return List.end(); }
691 BaseType::const_iterator begin() const { return List.begin(); }
692 BaseType::const_iterator end() const { return List.end(); }
693
694 BaseType List;
695
696 void print(raw_ostream &OS, const SelectionDAG &G) const;
697};
Benjamin Kramer802e6252017-12-24 12:46:22 +0000698} // namespace
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000699
700void OpRef::print(raw_ostream &OS, const SelectionDAG &G) const {
701 if (isValue()) {
702 OpV.getNode()->print(OS, &G);
703 return;
704 }
705 if (OpN & Invalid) {
706 OS << "invalid";
707 return;
708 }
709 if (OpN & Undef) {
710 OS << "undef";
711 return;
712 }
713 if ((OpN & Whole) != Whole) {
714 assert((OpN & Whole) == LoHalf || (OpN & Whole) == HiHalf);
715 if (OpN & LoHalf)
716 OS << "lo ";
717 else
718 OS << "hi ";
719 }
720 OS << '#' << SignExtend32(OpN & Index, IndexBits);
721}
722
723void NodeTemplate::print(raw_ostream &OS, const SelectionDAG &G) const {
724 const TargetInstrInfo &TII = *G.getSubtarget().getInstrInfo();
725 OS << format("%8s", EVT(Ty).getEVTString().c_str()) << " "
726 << TII.getName(Opc);
727 bool Comma = false;
728 for (const auto &R : Ops) {
729 if (Comma)
730 OS << ',';
731 Comma = true;
732 OS << ' ';
733 R.print(OS, G);
734 }
735}
736
737void ResultStack::print(raw_ostream &OS, const SelectionDAG &G) const {
738 OS << "Input node:\n";
Davide Italiano9c60c7d2017-12-06 18:54:17 +0000739#ifndef NDEBUG
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000740 InpNode->dumpr(&G);
Davide Italiano9c60c7d2017-12-06 18:54:17 +0000741#endif
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000742 OS << "Result templates:\n";
743 for (unsigned I = 0, E = List.size(); I != E; ++I) {
744 OS << '[' << I << "] ";
745 List[I].print(OS, G);
746 OS << '\n';
747 }
748}
749
Benjamin Kramer802e6252017-12-24 12:46:22 +0000750namespace {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000751struct ShuffleMask {
752 ShuffleMask(ArrayRef<int> M) : Mask(M) {
753 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
754 int M = Mask[I];
755 if (M == -1)
756 continue;
757 MinSrc = (MinSrc == -1) ? M : std::min(MinSrc, M);
758 MaxSrc = (MaxSrc == -1) ? M : std::max(MaxSrc, M);
759 }
760 }
761
762 ArrayRef<int> Mask;
763 int MinSrc = -1, MaxSrc = -1;
764
765 ShuffleMask lo() const {
766 size_t H = Mask.size()/2;
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +0000767 return ShuffleMask(Mask.take_front(H));
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000768 }
769 ShuffleMask hi() const {
770 size_t H = Mask.size()/2;
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +0000771 return ShuffleMask(Mask.take_back(H));
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000772 }
773};
Benjamin Kramer802e6252017-12-24 12:46:22 +0000774} // namespace
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000775
776// --------------------------------------------------------------------
777// The HvxSelector class.
778
779static const HexagonTargetLowering &getHexagonLowering(SelectionDAG &G) {
780 return static_cast<const HexagonTargetLowering&>(G.getTargetLoweringInfo());
781}
782static const HexagonSubtarget &getHexagonSubtarget(SelectionDAG &G) {
783 return static_cast<const HexagonSubtarget&>(G.getSubtarget());
784}
785
786namespace llvm {
787 struct HvxSelector {
788 const HexagonTargetLowering &Lower;
789 HexagonDAGToDAGISel &ISel;
790 SelectionDAG &DAG;
791 const HexagonSubtarget &HST;
792 const unsigned HwLen;
793
794 HvxSelector(HexagonDAGToDAGISel &HS, SelectionDAG &G)
795 : Lower(getHexagonLowering(G)), ISel(HS), DAG(G),
796 HST(getHexagonSubtarget(G)), HwLen(HST.getVectorLength()) {}
797
798 MVT getSingleVT(MVT ElemTy) const {
799 unsigned NumElems = HwLen / (ElemTy.getSizeInBits()/8);
800 return MVT::getVectorVT(ElemTy, NumElems);
801 }
802
803 MVT getPairVT(MVT ElemTy) const {
804 unsigned NumElems = (2*HwLen) / (ElemTy.getSizeInBits()/8);
805 return MVT::getVectorVT(ElemTy, NumElems);
806 }
807
808 void selectShuffle(SDNode *N);
809 void selectRor(SDNode *N);
810
811 private:
812 void materialize(const ResultStack &Results);
813
814 SDValue getVectorConstant(ArrayRef<uint8_t> Data, const SDLoc &dl);
815
816 enum : unsigned {
817 None,
818 PackMux,
819 };
820 OpRef concat(OpRef Va, OpRef Vb, ResultStack &Results);
821 OpRef packs(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
822 MutableArrayRef<int> NewMask, unsigned Options = None);
823 OpRef packp(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
824 MutableArrayRef<int> NewMask);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000825 OpRef vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
826 ResultStack &Results);
827 OpRef vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
828 ResultStack &Results);
829
830 OpRef shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results);
831 OpRef shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
832 OpRef shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results);
833 OpRef shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
834
835 OpRef butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results);
836 OpRef contracting(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
837 OpRef expanding(ShuffleMask SM, OpRef Va, ResultStack &Results);
838 OpRef perfect(ShuffleMask SM, OpRef Va, ResultStack &Results);
839
840 bool selectVectorConstants(SDNode *N);
841 bool scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl, MVT ResTy,
842 SDValue Va, SDValue Vb, SDNode *N);
843
844 };
845}
846
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000847static void splitMask(ArrayRef<int> Mask, MutableArrayRef<int> MaskL,
848 MutableArrayRef<int> MaskR) {
849 unsigned VecLen = Mask.size();
850 assert(MaskL.size() == VecLen && MaskR.size() == VecLen);
851 for (unsigned I = 0; I != VecLen; ++I) {
852 int M = Mask[I];
853 if (M < 0) {
854 MaskL[I] = MaskR[I] = -1;
855 } else if (unsigned(M) < VecLen) {
856 MaskL[I] = M;
857 MaskR[I] = -1;
858 } else {
859 MaskL[I] = -1;
860 MaskR[I] = M-VecLen;
861 }
862 }
863}
864
865static std::pair<int,unsigned> findStrip(ArrayRef<int> A, int Inc,
866 unsigned MaxLen) {
867 assert(A.size() > 0 && A.size() >= MaxLen);
868 int F = A[0];
869 int E = F;
870 for (unsigned I = 1; I != MaxLen; ++I) {
871 if (A[I] - E != Inc)
872 return { F, I };
873 E = A[I];
874 }
875 return { F, MaxLen };
876}
877
878static bool isUndef(ArrayRef<int> Mask) {
879 for (int Idx : Mask)
880 if (Idx != -1)
881 return false;
882 return true;
883}
884
885static bool isIdentity(ArrayRef<int> Mask) {
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +0000886 for (int I = 0, E = Mask.size(); I != E; ++I) {
887 int M = Mask[I];
888 if (M >= 0 && M != I)
889 return false;
890 }
891 return true;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000892}
893
894static bool isPermutation(ArrayRef<int> Mask) {
895 // Check by adding all numbers only works if there is no overflow.
896 assert(Mask.size() < 0x00007FFF && "Sanity failure");
897 int Sum = 0;
898 for (int Idx : Mask) {
899 if (Idx == -1)
900 return false;
901 Sum += Idx;
902 }
903 int N = Mask.size();
904 return 2*Sum == N*(N-1);
905}
906
907bool HvxSelector::selectVectorConstants(SDNode *N) {
908 // Constant vectors are generated as loads from constant pools.
909 // Since they are generated during the selection process, the main
910 // selection algorithm is not aware of them. Select them directly
911 // here.
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000912 SmallVector<SDNode*,4> Loads;
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000913 SetVector<SDNode*> WorkQ;
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000914
915 // The DAG can change (due to CSE) during selection, so cache all the
916 // unselected nodes first to avoid traversing a mutating DAG.
917
918 auto IsLoadToSelect = [] (SDNode *N) {
919 if (!N->isMachineOpcode() && N->getOpcode() == ISD::LOAD) {
920 SDValue Addr = cast<LoadSDNode>(N)->getBasePtr();
921 unsigned AddrOpc = Addr.getOpcode();
922 if (AddrOpc == HexagonISD::AT_PCREL || AddrOpc == HexagonISD::CP)
923 if (Addr.getOperand(0).getOpcode() == ISD::TargetConstantPool)
924 return true;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000925 }
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000926 return false;
927 };
928
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000929 WorkQ.insert(N);
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000930 for (unsigned i = 0; i != WorkQ.size(); ++i) {
931 SDNode *W = WorkQ[i];
932 if (IsLoadToSelect(W)) {
933 Loads.push_back(W);
934 continue;
935 }
936 for (unsigned j = 0, f = W->getNumOperands(); j != f; ++j)
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000937 WorkQ.insert(W->getOperand(j).getNode());
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000938 }
939
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000940 for (SDNode *L : Loads)
941 ISel.Select(L);
942
943 return !Loads.empty();
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000944}
945
946void HvxSelector::materialize(const ResultStack &Results) {
947 DEBUG_WITH_TYPE("isel", {
948 dbgs() << "Materializing\n";
949 Results.print(dbgs(), DAG);
950 });
951 if (Results.empty())
952 return;
953 const SDLoc &dl(Results.InpNode);
954 std::vector<SDValue> Output;
955
956 for (unsigned I = 0, E = Results.size(); I != E; ++I) {
957 const NodeTemplate &Node = Results[I];
958 std::vector<SDValue> Ops;
959 for (const OpRef &R : Node.Ops) {
960 assert(R.isValid());
961 if (R.isValue()) {
962 Ops.push_back(R.OpV);
963 continue;
964 }
965 if (R.OpN & OpRef::Undef) {
966 MVT::SimpleValueType SVT = MVT::SimpleValueType(R.OpN & OpRef::Index);
967 Ops.push_back(ISel.selectUndef(dl, MVT(SVT)));
968 continue;
969 }
970 // R is an index of a result.
971 unsigned Part = R.OpN & OpRef::Whole;
972 int Idx = SignExtend32(R.OpN & OpRef::Index, OpRef::IndexBits);
973 if (Idx < 0)
974 Idx += I;
975 assert(Idx >= 0 && unsigned(Idx) < Output.size());
976 SDValue Op = Output[Idx];
977 MVT OpTy = Op.getValueType().getSimpleVT();
978 if (Part != OpRef::Whole) {
979 assert(Part == OpRef::LoHalf || Part == OpRef::HiHalf);
980 if (Op.getOpcode() == HexagonISD::VCOMBINE) {
981 Op = (Part == OpRef::HiHalf) ? Op.getOperand(0) : Op.getOperand(1);
982 } else {
983 MVT HalfTy = MVT::getVectorVT(OpTy.getVectorElementType(),
984 OpTy.getVectorNumElements()/2);
985 unsigned Sub = (Part == OpRef::LoHalf) ? Hexagon::vsub_lo
986 : Hexagon::vsub_hi;
987 Op = DAG.getTargetExtractSubreg(Sub, dl, HalfTy, Op);
988 }
989 }
990 Ops.push_back(Op);
991 } // for (Node : Results)
992
993 assert(Node.Ty != MVT::Other);
994 SDNode *ResN = (Node.Opc == TargetOpcode::COPY)
995 ? Ops.front().getNode()
996 : DAG.getMachineNode(Node.Opc, dl, Node.Ty, Ops);
997 Output.push_back(SDValue(ResN, 0));
998 }
999
1000 SDNode *OutN = Output.back().getNode();
1001 SDNode *InpN = Results.InpNode;
1002 DEBUG_WITH_TYPE("isel", {
1003 dbgs() << "Generated node:\n";
1004 OutN->dumpr(&DAG);
1005 });
1006
1007 ISel.ReplaceNode(InpN, OutN);
1008 selectVectorConstants(OutN);
1009 DAG.RemoveDeadNodes();
1010}
1011
1012OpRef HvxSelector::concat(OpRef Lo, OpRef Hi, ResultStack &Results) {
1013 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1014 const SDLoc &dl(Results.InpNode);
1015 Results.push(TargetOpcode::REG_SEQUENCE, getPairVT(MVT::i8), {
1016 DAG.getTargetConstant(Hexagon::HvxWRRegClassID, dl, MVT::i32),
1017 Lo, DAG.getTargetConstant(Hexagon::vsub_lo, dl, MVT::i32),
1018 Hi, DAG.getTargetConstant(Hexagon::vsub_hi, dl, MVT::i32),
1019 });
1020 return OpRef::res(Results.top());
1021}
1022
1023// Va, Vb are single vectors, SM can be arbitrarily long.
1024OpRef HvxSelector::packs(ShuffleMask SM, OpRef Va, OpRef Vb,
1025 ResultStack &Results, MutableArrayRef<int> NewMask,
1026 unsigned Options) {
1027 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1028 if (!Va.isValid() || !Vb.isValid())
1029 return OpRef::fail();
1030
1031 int VecLen = SM.Mask.size();
1032 MVT Ty = getSingleVT(MVT::i8);
1033
1034 if (SM.MaxSrc - SM.MinSrc < int(HwLen)) {
1035 if (SM.MaxSrc < int(HwLen)) {
1036 memcpy(NewMask.data(), SM.Mask.data(), sizeof(int)*VecLen);
1037 return Va;
1038 }
1039 if (SM.MinSrc >= int(HwLen)) {
1040 for (int I = 0; I != VecLen; ++I) {
1041 int M = SM.Mask[I];
1042 if (M != -1)
1043 M -= HwLen;
1044 NewMask[I] = M;
1045 }
1046 return Vb;
1047 }
1048 const SDLoc &dl(Results.InpNode);
1049 SDValue S = DAG.getTargetConstant(SM.MinSrc, dl, MVT::i32);
1050 if (isUInt<3>(SM.MinSrc)) {
1051 Results.push(Hexagon::V6_valignbi, Ty, {Vb, Va, S});
1052 } else {
1053 Results.push(Hexagon::A2_tfrsi, MVT::i32, {S});
1054 unsigned Top = Results.top();
1055 Results.push(Hexagon::V6_valignb, Ty, {Vb, Va, OpRef::res(Top)});
1056 }
1057 for (int I = 0; I != VecLen; ++I) {
1058 int M = SM.Mask[I];
1059 if (M != -1)
1060 M -= SM.MinSrc;
1061 NewMask[I] = M;
1062 }
1063 return OpRef::res(Results.top());
1064 }
1065
1066 if (Options & PackMux) {
1067 // If elements picked from Va and Vb have all different (source) indexes
1068 // (relative to the start of the argument), do a mux, and update the mask.
1069 BitVector Picked(HwLen);
1070 SmallVector<uint8_t,128> MuxBytes(HwLen);
1071 bool CanMux = true;
1072 for (int I = 0; I != VecLen; ++I) {
1073 int M = SM.Mask[I];
1074 if (M == -1)
1075 continue;
1076 if (M >= int(HwLen))
1077 M -= HwLen;
1078 else
1079 MuxBytes[M] = 0xFF;
1080 if (Picked[M]) {
1081 CanMux = false;
1082 break;
1083 }
1084 NewMask[I] = M;
1085 }
1086 if (CanMux)
1087 return vmuxs(MuxBytes, Va, Vb, Results);
1088 }
1089
1090 return OpRef::fail();
1091}
1092
1093OpRef HvxSelector::packp(ShuffleMask SM, OpRef Va, OpRef Vb,
1094 ResultStack &Results, MutableArrayRef<int> NewMask) {
1095 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1096 unsigned HalfMask = 0;
1097 unsigned LogHw = Log2_32(HwLen);
1098 for (int M : SM.Mask) {
1099 if (M == -1)
1100 continue;
1101 HalfMask |= (1u << (M >> LogHw));
1102 }
1103
1104 if (HalfMask == 0)
1105 return OpRef::undef(getPairVT(MVT::i8));
1106
1107 // If more than two halves are used, bail.
1108 // TODO: be more aggressive here?
1109 if (countPopulation(HalfMask) > 2)
1110 return OpRef::fail();
1111
1112 MVT HalfTy = getSingleVT(MVT::i8);
1113
1114 OpRef Inp[2] = { Va, Vb };
1115 OpRef Out[2] = { OpRef::undef(HalfTy), OpRef::undef(HalfTy) };
1116
1117 uint8_t HalfIdx[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
1118 unsigned Idx = 0;
1119 for (unsigned I = 0; I != 4; ++I) {
1120 if ((HalfMask & (1u << I)) == 0)
1121 continue;
1122 assert(Idx < 2);
1123 OpRef Op = Inp[I/2];
1124 Out[Idx] = (I & 1) ? OpRef::hi(Op) : OpRef::lo(Op);
1125 HalfIdx[I] = Idx++;
1126 }
1127
1128 int VecLen = SM.Mask.size();
1129 for (int I = 0; I != VecLen; ++I) {
1130 int M = SM.Mask[I];
1131 if (M >= 0) {
1132 uint8_t Idx = HalfIdx[M >> LogHw];
1133 assert(Idx == 0 || Idx == 1);
1134 M = (M & (HwLen-1)) + HwLen*Idx;
1135 }
1136 NewMask[I] = M;
1137 }
1138
1139 return concat(Out[0], Out[1], Results);
1140}
1141
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001142OpRef HvxSelector::vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1143 ResultStack &Results) {
1144 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1145 MVT ByteTy = getSingleVT(MVT::i8);
1146 MVT BoolTy = MVT::getVectorVT(MVT::i1, 8*HwLen); // XXX
1147 const SDLoc &dl(Results.InpNode);
1148 SDValue B = getVectorConstant(Bytes, dl);
1149 Results.push(Hexagon::V6_vd0, ByteTy, {});
1150 Results.push(Hexagon::V6_veqb, BoolTy, {OpRef(B), OpRef::res(-1)});
Krzysztof Parzyszek40a605f2017-12-12 19:32:41 +00001151 Results.push(Hexagon::V6_vmux, ByteTy, {OpRef::res(-1), Vb, Va});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001152 return OpRef::res(Results.top());
1153}
1154
1155OpRef HvxSelector::vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1156 ResultStack &Results) {
1157 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1158 size_t S = Bytes.size() / 2;
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001159 OpRef L = vmuxs(Bytes.take_front(S), OpRef::lo(Va), OpRef::lo(Vb), Results);
1160 OpRef H = vmuxs(Bytes.drop_front(S), OpRef::hi(Va), OpRef::hi(Vb), Results);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001161 return concat(L, H, Results);
1162}
1163
1164OpRef HvxSelector::shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1165 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1166 unsigned VecLen = SM.Mask.size();
1167 assert(HwLen == VecLen);
Tim Shenb684b1a2017-12-06 19:33:42 +00001168 (void)VecLen;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001169 assert(all_of(SM.Mask, [this](int M) { return M == -1 || M < int(HwLen); }));
1170
1171 if (isIdentity(SM.Mask))
1172 return Va;
1173 if (isUndef(SM.Mask))
1174 return OpRef::undef(getSingleVT(MVT::i8));
1175
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001176 OpRef P = perfect(SM, Va, Results);
1177 if (P.isValid())
1178 return P;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001179 return butterfly(SM, Va, Results);
1180}
1181
1182OpRef HvxSelector::shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb,
1183 ResultStack &Results) {
1184 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001185 if (isUndef(SM.Mask))
1186 return OpRef::undef(getSingleVT(MVT::i8));
1187
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001188 OpRef C = contracting(SM, Va, Vb, Results);
1189 if (C.isValid())
1190 return C;
1191
1192 int VecLen = SM.Mask.size();
1193 SmallVector<int,128> NewMask(VecLen);
1194 OpRef P = packs(SM, Va, Vb, Results, NewMask);
1195 if (P.isValid())
1196 return shuffs1(ShuffleMask(NewMask), P, Results);
1197
1198 SmallVector<int,128> MaskL(VecLen), MaskR(VecLen);
1199 splitMask(SM.Mask, MaskL, MaskR);
1200
1201 OpRef L = shuffs1(ShuffleMask(MaskL), Va, Results);
1202 OpRef R = shuffs1(ShuffleMask(MaskR), Vb, Results);
1203 if (!L.isValid() || !R.isValid())
1204 return OpRef::fail();
1205
1206 SmallVector<uint8_t,128> Bytes(VecLen);
1207 for (int I = 0; I != VecLen; ++I) {
1208 if (MaskL[I] != -1)
1209 Bytes[I] = 0xFF;
1210 }
1211 return vmuxs(Bytes, L, R, Results);
1212}
1213
1214OpRef HvxSelector::shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1215 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1216 int VecLen = SM.Mask.size();
1217
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001218 if (isIdentity(SM.Mask))
1219 return Va;
1220 if (isUndef(SM.Mask))
1221 return OpRef::undef(getPairVT(MVT::i8));
1222
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001223 SmallVector<int,128> PackedMask(VecLen);
1224 OpRef P = packs(SM, OpRef::lo(Va), OpRef::hi(Va), Results, PackedMask);
1225 if (P.isValid()) {
1226 ShuffleMask PM(PackedMask);
1227 OpRef E = expanding(PM, P, Results);
1228 if (E.isValid())
1229 return E;
1230
1231 OpRef L = shuffs1(PM.lo(), P, Results);
1232 OpRef H = shuffs1(PM.hi(), P, Results);
1233 if (L.isValid() && H.isValid())
1234 return concat(L, H, Results);
1235 }
1236
1237 OpRef R = perfect(SM, Va, Results);
1238 if (R.isValid())
1239 return R;
1240 // TODO commute the mask and try the opposite order of the halves.
1241
1242 OpRef L = shuffs2(SM.lo(), OpRef::lo(Va), OpRef::hi(Va), Results);
1243 OpRef H = shuffs2(SM.hi(), OpRef::lo(Va), OpRef::hi(Va), Results);
1244 if (L.isValid() && H.isValid())
1245 return concat(L, H, Results);
1246
1247 return OpRef::fail();
1248}
1249
1250OpRef HvxSelector::shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb,
1251 ResultStack &Results) {
1252 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001253 if (isUndef(SM.Mask))
1254 return OpRef::undef(getPairVT(MVT::i8));
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001255
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001256 int VecLen = SM.Mask.size();
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001257 SmallVector<int,256> PackedMask(VecLen);
1258 OpRef P = packp(SM, Va, Vb, Results, PackedMask);
1259 if (P.isValid())
1260 return shuffp1(ShuffleMask(PackedMask), P, Results);
1261
1262 SmallVector<int,256> MaskL(VecLen), MaskR(VecLen);
1263 OpRef L = shuffp1(ShuffleMask(MaskL), Va, Results);
1264 OpRef R = shuffp1(ShuffleMask(MaskR), Vb, Results);
1265 if (!L.isValid() || !R.isValid())
1266 return OpRef::fail();
1267
1268 // Mux the results.
1269 SmallVector<uint8_t,256> Bytes(VecLen);
1270 for (int I = 0; I != VecLen; ++I) {
1271 if (MaskL[I] != -1)
1272 Bytes[I] = 0xFF;
1273 }
1274 return vmuxp(Bytes, L, R, Results);
1275}
1276
1277bool HvxSelector::scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl,
1278 MVT ResTy, SDValue Va, SDValue Vb,
1279 SDNode *N) {
1280 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1281 MVT ElemTy = ResTy.getVectorElementType();
1282 assert(ElemTy == MVT::i8);
1283 unsigned VecLen = Mask.size();
1284 bool HavePairs = (2*HwLen == VecLen);
1285 MVT SingleTy = getSingleVT(MVT::i8);
1286
1287 SmallVector<SDValue,128> Ops;
1288 for (int I : Mask) {
1289 if (I < 0) {
1290 Ops.push_back(ISel.selectUndef(dl, ElemTy));
1291 continue;
1292 }
1293 SDValue Vec;
1294 unsigned M = I;
1295 if (M < VecLen) {
1296 Vec = Va;
1297 } else {
1298 Vec = Vb;
1299 M -= VecLen;
1300 }
1301 if (HavePairs) {
1302 if (M < HwLen) {
1303 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, SingleTy, Vec);
1304 } else {
1305 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, SingleTy, Vec);
1306 M -= HwLen;
1307 }
1308 }
1309 SDValue Idx = DAG.getConstant(M, dl, MVT::i32);
1310 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ElemTy, {Vec, Idx});
1311 SDValue L = Lower.LowerOperation(Ex, DAG);
1312 assert(L.getNode());
1313 Ops.push_back(L);
1314 }
1315
1316 SDValue LV;
1317 if (2*HwLen == VecLen) {
1318 SDValue B0 = DAG.getBuildVector(SingleTy, dl, {Ops.data(), HwLen});
1319 SDValue L0 = Lower.LowerOperation(B0, DAG);
1320 SDValue B1 = DAG.getBuildVector(SingleTy, dl, {Ops.data()+HwLen, HwLen});
1321 SDValue L1 = Lower.LowerOperation(B1, DAG);
1322 // XXX CONCAT_VECTORS is legal for HVX vectors. Legalizing (lowering)
1323 // functions may expect to be called only for illegal operations, so
1324 // make sure that they are not called for legal ones. Develop a better
1325 // mechanism for dealing with this.
1326 LV = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, {L0, L1});
1327 } else {
1328 SDValue BV = DAG.getBuildVector(ResTy, dl, Ops);
1329 LV = Lower.LowerOperation(BV, DAG);
1330 }
1331
1332 assert(!N->use_empty());
1333 ISel.ReplaceNode(N, LV.getNode());
1334 DAG.RemoveDeadNodes();
1335
1336 std::deque<SDNode*> SubNodes;
1337 SubNodes.push_back(LV.getNode());
1338 for (unsigned I = 0; I != SubNodes.size(); ++I) {
1339 for (SDValue Op : SubNodes[I]->ops())
1340 SubNodes.push_back(Op.getNode());
1341 }
1342 while (!SubNodes.empty()) {
1343 SDNode *S = SubNodes.front();
1344 SubNodes.pop_front();
1345 if (S->use_empty())
1346 continue;
1347 // This isn't great, but users need to be selected before any nodes that
1348 // they use. (The reason is to match larger patterns, and avoid nodes that
1349 // cannot be matched on their own, e.g. ValueType, TokenFactor, etc.).
1350 bool PendingUser = llvm::any_of(S->uses(), [&SubNodes](const SDNode *U) {
1351 return llvm::any_of(SubNodes, [U](const SDNode *T) {
1352 return T == U;
1353 });
1354 });
1355 if (PendingUser)
1356 SubNodes.push_back(S);
1357 else
1358 ISel.Select(S);
1359 }
1360
1361 DAG.RemoveDeadNodes();
1362 return true;
1363}
1364
1365OpRef HvxSelector::contracting(ShuffleMask SM, OpRef Va, OpRef Vb,
1366 ResultStack &Results) {
1367 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1368 if (!Va.isValid() || !Vb.isValid())
1369 return OpRef::fail();
1370
1371 // Contracting shuffles, i.e. instructions that always discard some bytes
1372 // from the operand vectors.
1373 //
1374 // V6_vshuff{e,o}b
1375 // V6_vdealb4w
1376 // V6_vpack{e,o}{b,h}
1377
1378 int VecLen = SM.Mask.size();
1379 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1380 MVT ResTy = getSingleVT(MVT::i8);
1381
1382 // The following shuffles only work for bytes and halfwords. This requires
1383 // the strip length to be 1 or 2.
1384 if (Strip.second != 1 && Strip.second != 2)
1385 return OpRef::fail();
1386
1387 // The patterns for the shuffles, in terms of the starting offsets of the
1388 // consecutive strips (L = length of the strip, N = VecLen):
1389 //
1390 // vpacke: 0, 2L, 4L ... N+0, N+2L, N+4L ... L = 1 or 2
1391 // vpacko: L, 3L, 5L ... N+L, N+3L, N+5L ... L = 1 or 2
1392 //
1393 // vshuffe: 0, N+0, 2L, N+2L, 4L ... L = 1 or 2
1394 // vshuffo: L, N+L, 3L, N+3L, 5L ... L = 1 or 2
1395 //
1396 // vdealb4w: 0, 4, 8 ... 2, 6, 10 ... N+0, N+4, N+8 ... N+2, N+6, N+10 ...
1397
1398 // The value of the element in the mask following the strip will decide
1399 // what kind of a shuffle this can be.
1400 int NextInMask = SM.Mask[Strip.second];
1401
1402 // Check if NextInMask could be 2L, 3L or 4, i.e. if it could be a mask
1403 // for vpack or vdealb4w. VecLen > 4, so NextInMask for vdealb4w would
1404 // satisfy this.
1405 if (NextInMask < VecLen) {
1406 // vpack{e,o} or vdealb4w
1407 if (Strip.first == 0 && Strip.second == 1 && NextInMask == 4) {
1408 int N = VecLen;
1409 // Check if this is vdealb4w (L=1).
1410 for (int I = 0; I != N/4; ++I)
1411 if (SM.Mask[I] != 4*I)
1412 return OpRef::fail();
1413 for (int I = 0; I != N/4; ++I)
1414 if (SM.Mask[I+N/4] != 2 + 4*I)
1415 return OpRef::fail();
1416 for (int I = 0; I != N/4; ++I)
1417 if (SM.Mask[I+N/2] != N + 4*I)
1418 return OpRef::fail();
1419 for (int I = 0; I != N/4; ++I)
1420 if (SM.Mask[I+3*N/4] != N+2 + 4*I)
1421 return OpRef::fail();
1422 // Matched mask for vdealb4w.
1423 Results.push(Hexagon::V6_vdealb4w, ResTy, {Vb, Va});
1424 return OpRef::res(Results.top());
1425 }
1426
1427 // Check if this is vpack{e,o}.
1428 int N = VecLen;
1429 int L = Strip.second;
1430 // Check if the first strip starts at 0 or at L.
1431 if (Strip.first != 0 && Strip.first != L)
1432 return OpRef::fail();
1433 // Examine the rest of the mask.
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001434 for (int I = L; I < N; I += L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001435 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001436 // Check whether the mask element at the beginning of each strip
1437 // increases by 2L each time.
1438 if (S.first - Strip.first != 2*I)
1439 return OpRef::fail();
1440 // Check whether each strip is of the same length.
1441 if (S.second != unsigned(L))
1442 return OpRef::fail();
1443 }
1444
1445 // Strip.first == 0 => vpacke
1446 // Strip.first == L => vpacko
1447 assert(Strip.first == 0 || Strip.first == L);
1448 using namespace Hexagon;
1449 NodeTemplate Res;
1450 Res.Opc = Strip.second == 1 // Number of bytes.
1451 ? (Strip.first == 0 ? V6_vpackeb : V6_vpackob)
1452 : (Strip.first == 0 ? V6_vpackeh : V6_vpackoh);
1453 Res.Ty = ResTy;
1454 Res.Ops = { Vb, Va };
1455 Results.push(Res);
1456 return OpRef::res(Results.top());
1457 }
1458
1459 // Check if this is vshuff{e,o}.
1460 int N = VecLen;
1461 int L = Strip.second;
1462 std::pair<int,unsigned> PrevS = Strip;
1463 bool Flip = false;
1464 for (int I = L; I < N; I += L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001465 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001466 if (S.second != PrevS.second)
1467 return OpRef::fail();
1468 int Diff = Flip ? PrevS.first - S.first + 2*L
1469 : S.first - PrevS.first;
1470 if (Diff != N)
1471 return OpRef::fail();
1472 Flip ^= true;
1473 PrevS = S;
1474 }
1475 // Strip.first == 0 => vshuffe
1476 // Strip.first == L => vshuffo
1477 assert(Strip.first == 0 || Strip.first == L);
1478 using namespace Hexagon;
1479 NodeTemplate Res;
1480 Res.Opc = Strip.second == 1 // Number of bytes.
1481 ? (Strip.first == 0 ? V6_vshuffeb : V6_vshuffob)
1482 : (Strip.first == 0 ? V6_vshufeh : V6_vshufoh);
1483 Res.Ty = ResTy;
1484 Res.Ops = { Vb, Va };
1485 Results.push(Res);
1486 return OpRef::res(Results.top());
1487}
1488
1489OpRef HvxSelector::expanding(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1490 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1491 // Expanding shuffles (using all elements and inserting into larger vector):
1492 //
1493 // V6_vunpacku{b,h} [*]
1494 //
1495 // [*] Only if the upper elements (filled with 0s) are "don't care" in Mask.
1496 //
1497 // Note: V6_vunpacko{b,h} are or-ing the high byte/half in the result, so
1498 // they are not shuffles.
1499 //
1500 // The argument is a single vector.
1501
1502 int VecLen = SM.Mask.size();
1503 assert(2*HwLen == unsigned(VecLen) && "Expecting vector-pair type");
1504
1505 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1506
1507 // The patterns for the unpacks, in terms of the starting offsets of the
1508 // consecutive strips (L = length of the strip, N = VecLen):
1509 //
1510 // vunpacku: 0, -1, L, -1, 2L, -1 ...
1511
1512 if (Strip.first != 0)
1513 return OpRef::fail();
1514
1515 // The vunpackus only handle byte and half-word.
1516 if (Strip.second != 1 && Strip.second != 2)
1517 return OpRef::fail();
1518
1519 int N = VecLen;
1520 int L = Strip.second;
1521
1522 // First, check the non-ignored strips.
1523 for (int I = 2*L; I < 2*N; I += 2*L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001524 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001525 if (S.second != unsigned(L))
1526 return OpRef::fail();
1527 if (2*S.first != I)
1528 return OpRef::fail();
1529 }
1530 // Check the -1s.
1531 for (int I = L; I < 2*N; I += 2*L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001532 auto S = findStrip(SM.Mask.drop_front(I), 0, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001533 if (S.first != -1 || S.second != unsigned(L))
1534 return OpRef::fail();
1535 }
1536
1537 unsigned Opc = Strip.second == 1 ? Hexagon::V6_vunpackub
1538 : Hexagon::V6_vunpackuh;
1539 Results.push(Opc, getPairVT(MVT::i8), {Va});
1540 return OpRef::res(Results.top());
1541}
1542
1543OpRef HvxSelector::perfect(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1544 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1545 // V6_vdeal{b,h}
1546 // V6_vshuff{b,h}
1547
1548 // V6_vshufoe{b,h} those are quivalent to vshuffvdd(..,{1,2})
1549 // V6_vshuffvdd (V6_vshuff)
1550 // V6_dealvdd (V6_vdeal)
1551
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001552 int VecLen = SM.Mask.size();
1553 assert(isPowerOf2_32(VecLen) && Log2_32(VecLen) <= 8);
1554 unsigned LogLen = Log2_32(VecLen);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001555 unsigned HwLog = Log2_32(HwLen);
1556 // The result length must be the same as the length of a single vector,
1557 // or a vector pair.
1558 assert(LogLen == HwLog || LogLen == HwLog+1);
1559 bool Extend = (LogLen == HwLog);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001560
1561 if (!isPermutation(SM.Mask))
1562 return OpRef::fail();
1563
1564 SmallVector<unsigned,8> Perm(LogLen);
1565
1566 // Check if this could be a perfect shuffle, or a combination of perfect
1567 // shuffles.
1568 //
1569 // Consider this permutation (using hex digits to make the ASCII diagrams
1570 // easier to read):
1571 // { 0, 8, 1, 9, 2, A, 3, B, 4, C, 5, D, 6, E, 7, F }.
1572 // This is a "deal" operation: divide the input into two halves, and
1573 // create the output by picking elements by alternating between these two
1574 // halves:
1575 // 0 1 2 3 4 5 6 7 --> 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F [*]
1576 // 8 9 A B C D E F
1577 //
1578 // Aside from a few special explicit cases (V6_vdealb, etc.), HVX provides
1579 // a somwehat different mechanism that could be used to perform shuffle/
1580 // deal operations: a 2x2 transpose.
1581 // Consider the halves of inputs again, they can be interpreted as a 2x8
1582 // matrix. A 2x8 matrix can be looked at four 2x2 matrices concatenated
1583 // together. Now, when considering 2 elements at a time, it will be a 2x4
1584 // matrix (with elements 01, 23, 45, etc.), or two 2x2 matrices:
1585 // 01 23 45 67
1586 // 89 AB CD EF
1587 // With groups of 4, this will become a single 2x2 matrix, and so on.
1588 //
1589 // The 2x2 transpose instruction works by transposing each of the 2x2
1590 // matrices (or "sub-matrices"), given a specific group size. For example,
1591 // if the group size is 1 (i.e. each element is its own group), there
1592 // will be four transposes of the four 2x2 matrices that form the 2x8.
1593 // For example, with the inputs as above, the result will be:
1594 // 0 8 2 A 4 C 6 E
1595 // 1 9 3 B 5 D 7 F
1596 // Now, this result can be tranposed again, but with the group size of 2:
1597 // 08 19 4C 5D
1598 // 2A 3B 6E 7F
1599 // If we then transpose that result, but with the group size of 4, we get:
1600 // 0819 2A3B
1601 // 4C5D 6E7F
1602 // If we concatenate these two rows, it will be
1603 // 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F
1604 // which is the same as the "deal" [*] above.
1605 //
1606 // In general, a "deal" of individual elements is a series of 2x2 transposes,
1607 // with changing group size. HVX has two instructions:
1608 // Vdd = V6_vdealvdd Vu, Vv, Rt
1609 // Vdd = V6_shufvdd Vu, Vv, Rt
1610 // that perform exactly that. The register Rt controls which transposes are
1611 // going to happen: a bit at position n (counting from 0) indicates that a
1612 // transpose with a group size of 2^n will take place. If multiple bits are
1613 // set, multiple transposes will happen: vdealvdd will perform them starting
1614 // with the largest group size, vshuffvdd will do them in the reverse order.
1615 //
1616 // The main observation is that each 2x2 transpose corresponds to swapping
1617 // columns of bits in the binary representation of the values.
1618 //
1619 // The numbers {3,2,1,0} and the log2 of the number of contiguous 1 bits
1620 // in a given column. The * denote the columns that will be swapped.
1621 // The transpose with the group size 2^n corresponds to swapping columns
1622 // 3 (the highest log) and log2(n):
1623 //
1624 // 3 2 1 0 0 2 1 3 0 2 3 1
1625 // * * * * * *
1626 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1627 // 1 0 0 0 1 8 1 0 0 0 8 1 0 0 0 8 1 0 0 0
1628 // 2 0 0 1 0 2 0 0 1 0 1 0 0 0 1 1 0 0 0 1
1629 // 3 0 0 1 1 A 1 0 1 0 9 1 0 0 1 9 1 0 0 1
1630 // 4 0 1 0 0 4 0 1 0 0 4 0 1 0 0 2 0 0 1 0
1631 // 5 0 1 0 1 C 1 1 0 0 C 1 1 0 0 A 1 0 1 0
1632 // 6 0 1 1 0 6 0 1 1 0 5 0 1 0 1 3 0 0 1 1
1633 // 7 0 1 1 1 E 1 1 1 0 D 1 1 0 1 B 1 0 1 1
1634 // 8 1 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 1 0 0
1635 // 9 1 0 0 1 9 1 0 0 1 A 1 0 1 0 C 1 1 0 0
1636 // A 1 0 1 0 3 0 0 1 1 3 0 0 1 1 5 0 1 0 1
1637 // B 1 0 1 1 B 1 0 1 1 B 1 0 1 1 D 1 1 0 1
1638 // C 1 1 0 0 5 0 1 0 1 6 0 1 1 0 6 0 1 1 0
1639 // D 1 1 0 1 D 1 1 0 1 E 1 1 1 0 E 1 1 1 0
1640 // E 1 1 1 0 7 0 1 1 1 7 0 1 1 1 7 0 1 1 1
1641 // F 1 1 1 1 F 1 1 1 1 F 1 1 1 1 F 1 1 1 1
1642
1643 auto XorPow2 = [] (ArrayRef<int> Mask, unsigned Num) {
1644 unsigned X = Mask[0] ^ Mask[Num/2];
1645 // Check that the first half has the X's bits clear.
1646 if ((Mask[0] & X) != 0)
1647 return 0u;
1648 for (unsigned I = 1; I != Num/2; ++I) {
1649 if (unsigned(Mask[I] ^ Mask[I+Num/2]) != X)
1650 return 0u;
1651 if ((Mask[I] & X) != 0)
1652 return 0u;
1653 }
1654 return X;
1655 };
1656
1657 // Create a vector of log2's for each column: Perm[i] corresponds to
1658 // the i-th bit (lsb is 0).
1659 assert(VecLen > 2);
1660 for (unsigned I = VecLen; I >= 2; I >>= 1) {
1661 // Examine the initial segment of Mask of size I.
1662 unsigned X = XorPow2(SM.Mask, I);
1663 if (!isPowerOf2_32(X))
1664 return OpRef::fail();
1665 // Check the other segments of Mask.
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001666 for (int J = I; J < VecLen; J += I) {
1667 if (XorPow2(SM.Mask.slice(J, I), I) != X)
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001668 return OpRef::fail();
1669 }
1670 Perm[Log2_32(X)] = Log2_32(I)-1;
1671 }
1672
1673 // Once we have Perm, represent it as cycles. Denote the maximum log2
1674 // (equal to log2(VecLen)-1) as M. The cycle containing M can then be
1675 // written as (M a1 a2 a3 ... an). That cycle can be broken up into
1676 // simple swaps as (M a1)(M a2)(M a3)...(M an), with the composition
1677 // order being from left to right. Any (contiguous) segment where the
1678 // values ai, ai+1...aj are either all increasing or all decreasing,
1679 // can be implemented via a single vshuffvdd/vdealvdd respectively.
1680 //
1681 // If there is a cycle (a1 a2 ... an) that does not involve M, it can
1682 // be written as (M an)(a1 a2 ... an)(M a1). The first two cycles can
1683 // then be folded to get (M a1 a2 ... an)(M a1), and the above procedure
1684 // can be used to generate a sequence of vshuffvdd/vdealvdd.
1685 //
1686 // Example:
1687 // Assume M = 4 and consider a permutation (0 1)(2 3). It can be written
1688 // as (4 0 1)(4 0) composed with (4 2 3)(4 2), or simply
1689 // (4 0 1)(4 0)(4 2 3)(4 2).
1690 // It can then be expanded into swaps as
1691 // (4 0)(4 1)(4 0)(4 2)(4 3)(4 2),
1692 // and broken up into "increasing" segments as
1693 // [(4 0)(4 1)] [(4 0)(4 2)(4 3)] [(4 2)].
1694 // This is equivalent to
1695 // (4 0 1)(4 0 2 3)(4 2),
1696 // which can be implemented as 3 vshufvdd instructions.
1697
1698 using CycleType = SmallVector<unsigned,8>;
1699 std::set<CycleType> Cycles;
1700 std::set<unsigned> All;
1701
1702 for (unsigned I : Perm)
1703 All.insert(I);
1704
1705 // If the cycle contains LogLen-1, move it to the front of the cycle.
1706 // Otherwise, return the cycle unchanged.
1707 auto canonicalize = [LogLen](const CycleType &C) -> CycleType {
1708 unsigned LogPos, N = C.size();
1709 for (LogPos = 0; LogPos != N; ++LogPos)
1710 if (C[LogPos] == LogLen-1)
1711 break;
1712 if (LogPos == N)
1713 return C;
1714
1715 CycleType NewC(C.begin()+LogPos, C.end());
1716 NewC.append(C.begin(), C.begin()+LogPos);
1717 return NewC;
1718 };
1719
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001720 auto pfs = [](const std::set<CycleType> &Cs, unsigned Len) {
1721 // Ordering: shuff: 5 0 1 2 3 4, deal: 5 4 3 2 1 0 (for Log=6),
1722 // for bytes zero is included, for halfwords is not.
1723 if (Cs.size() != 1)
1724 return 0u;
1725 const CycleType &C = *Cs.begin();
1726 if (C[0] != Len-1)
1727 return 0u;
1728 int D = Len - C.size();
1729 if (D != 0 && D != 1)
1730 return 0u;
1731
1732 bool IsDeal = true, IsShuff = true;
1733 for (unsigned I = 1; I != Len-D; ++I) {
1734 if (C[I] != Len-1-I)
1735 IsDeal = false;
1736 if (C[I] != I-(1-D)) // I-1, I
1737 IsShuff = false;
1738 }
1739 // At most one, IsDeal or IsShuff, can be non-zero.
1740 assert(!(IsDeal || IsShuff) || IsDeal != IsShuff);
1741 static unsigned Deals[] = { Hexagon::V6_vdealb, Hexagon::V6_vdealh };
1742 static unsigned Shufs[] = { Hexagon::V6_vshuffb, Hexagon::V6_vshuffh };
1743 return IsDeal ? Deals[D] : (IsShuff ? Shufs[D] : 0);
1744 };
1745
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001746 while (!All.empty()) {
1747 unsigned A = *All.begin();
1748 All.erase(A);
1749 CycleType C;
1750 C.push_back(A);
1751 for (unsigned B = Perm[A]; B != A; B = Perm[B]) {
1752 C.push_back(B);
1753 All.erase(B);
1754 }
1755 if (C.size() <= 1)
1756 continue;
1757 Cycles.insert(canonicalize(C));
1758 }
1759
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001760 MVT SingleTy = getSingleVT(MVT::i8);
1761 MVT PairTy = getPairVT(MVT::i8);
1762
1763 // Recognize patterns for V6_vdeal{b,h} and V6_vshuff{b,h}.
1764 if (unsigned(VecLen) == HwLen) {
1765 if (unsigned SingleOpc = pfs(Cycles, LogLen)) {
1766 Results.push(SingleOpc, SingleTy, {Va});
1767 return OpRef::res(Results.top());
1768 }
1769 }
1770
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001771 SmallVector<unsigned,8> SwapElems;
1772 if (HwLen == unsigned(VecLen))
1773 SwapElems.push_back(LogLen-1);
1774
1775 for (const CycleType &C : Cycles) {
1776 unsigned First = (C[0] == LogLen-1) ? 1 : 0;
1777 SwapElems.append(C.begin()+First, C.end());
1778 if (First == 0)
1779 SwapElems.push_back(C[0]);
1780 }
1781
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001782 const SDLoc &dl(Results.InpNode);
1783 OpRef Arg = !Extend ? Va
1784 : concat(Va, OpRef::undef(SingleTy), Results);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001785
1786 for (unsigned I = 0, E = SwapElems.size(); I != E; ) {
1787 bool IsInc = I == E-1 || SwapElems[I] < SwapElems[I+1];
1788 unsigned S = (1u << SwapElems[I]);
1789 if (I < E-1) {
1790 while (++I < E-1 && IsInc == (SwapElems[I] < SwapElems[I+1]))
1791 S |= 1u << SwapElems[I];
1792 // The above loop will not add a bit for the final SwapElems[I+1],
1793 // so add it here.
1794 S |= 1u << SwapElems[I];
1795 }
1796 ++I;
1797
1798 NodeTemplate Res;
1799 Results.push(Hexagon::A2_tfrsi, MVT::i32,
1800 { DAG.getTargetConstant(S, dl, MVT::i32) });
1801 Res.Opc = IsInc ? Hexagon::V6_vshuffvdd : Hexagon::V6_vdealvdd;
1802 Res.Ty = PairTy;
1803 Res.Ops = { OpRef::hi(Arg), OpRef::lo(Arg), OpRef::res(-1) };
1804 Results.push(Res);
1805 Arg = OpRef::res(Results.top());
1806 }
1807
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001808 return !Extend ? Arg : OpRef::lo(Arg);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001809}
1810
1811OpRef HvxSelector::butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1812 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1813 // Butterfly shuffles.
1814 //
1815 // V6_vdelta
1816 // V6_vrdelta
1817 // V6_vror
1818
1819 // The assumption here is that all elements picked by Mask are in the
1820 // first operand to the vector_shuffle. This assumption is enforced
1821 // by the caller.
1822
1823 MVT ResTy = getSingleVT(MVT::i8);
1824 PermNetwork::Controls FC, RC;
1825 const SDLoc &dl(Results.InpNode);
1826 int VecLen = SM.Mask.size();
1827
1828 for (int M : SM.Mask) {
1829 if (M != -1 && M >= VecLen)
1830 return OpRef::fail();
1831 }
1832
1833 // Try the deltas/benes for both single vectors and vector pairs.
1834 ForwardDeltaNetwork FN(SM.Mask);
1835 if (FN.run(FC)) {
1836 SDValue Ctl = getVectorConstant(FC, dl);
1837 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(Ctl)});
1838 return OpRef::res(Results.top());
1839 }
1840
1841 // Try reverse delta.
1842 ReverseDeltaNetwork RN(SM.Mask);
1843 if (RN.run(RC)) {
1844 SDValue Ctl = getVectorConstant(RC, dl);
1845 Results.push(Hexagon::V6_vrdelta, ResTy, {Va, OpRef(Ctl)});
1846 return OpRef::res(Results.top());
1847 }
1848
1849 // Do Benes.
1850 BenesNetwork BN(SM.Mask);
1851 if (BN.run(FC, RC)) {
1852 SDValue CtlF = getVectorConstant(FC, dl);
1853 SDValue CtlR = getVectorConstant(RC, dl);
1854 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(CtlF)});
1855 Results.push(Hexagon::V6_vrdelta, ResTy,
1856 {OpRef::res(-1), OpRef(CtlR)});
1857 return OpRef::res(Results.top());
1858 }
1859
1860 return OpRef::fail();
1861}
1862
1863SDValue HvxSelector::getVectorConstant(ArrayRef<uint8_t> Data,
1864 const SDLoc &dl) {
1865 SmallVector<SDValue, 128> Elems;
1866 for (uint8_t C : Data)
1867 Elems.push_back(DAG.getConstant(C, dl, MVT::i8));
1868 MVT VecTy = MVT::getVectorVT(MVT::i8, Data.size());
1869 SDValue BV = DAG.getBuildVector(VecTy, dl, Elems);
1870 SDValue LV = Lower.LowerOperation(BV, DAG);
1871 DAG.RemoveDeadNode(BV.getNode());
1872 return LV;
1873}
1874
1875void HvxSelector::selectShuffle(SDNode *N) {
1876 DEBUG_WITH_TYPE("isel", {
1877 dbgs() << "Starting " << __func__ << " on node:\n";
1878 N->dump(&DAG);
1879 });
1880 MVT ResTy = N->getValueType(0).getSimpleVT();
1881 // Assume that vector shuffles operate on vectors of bytes.
1882 assert(ResTy.isVector() && ResTy.getVectorElementType() == MVT::i8);
1883
1884 auto *SN = cast<ShuffleVectorSDNode>(N);
1885 std::vector<int> Mask(SN->getMask().begin(), SN->getMask().end());
1886 // This shouldn't really be necessary. Is it?
1887 for (int &Idx : Mask)
1888 if (Idx != -1 && Idx < 0)
1889 Idx = -1;
1890
1891 unsigned VecLen = Mask.size();
1892 bool HavePairs = (2*HwLen == VecLen);
1893 assert(ResTy.getSizeInBits() / 8 == VecLen);
1894
1895 // Vd = vector_shuffle Va, Vb, Mask
1896 //
1897
1898 bool UseLeft = false, UseRight = false;
1899 for (unsigned I = 0; I != VecLen; ++I) {
1900 if (Mask[I] == -1)
1901 continue;
1902 unsigned Idx = Mask[I];
1903 assert(Idx < 2*VecLen);
1904 if (Idx < VecLen)
1905 UseLeft = true;
1906 else
1907 UseRight = true;
1908 }
1909
1910 DEBUG_WITH_TYPE("isel", {
1911 dbgs() << "VecLen=" << VecLen << " HwLen=" << HwLen << " UseLeft="
1912 << UseLeft << " UseRight=" << UseRight << " HavePairs="
1913 << HavePairs << '\n';
1914 });
1915 // If the mask is all -1's, generate "undef".
1916 if (!UseLeft && !UseRight) {
1917 ISel.ReplaceNode(N, ISel.selectUndef(SDLoc(SN), ResTy).getNode());
1918 DAG.RemoveDeadNode(N);
1919 return;
1920 }
1921
1922 SDValue Vec0 = N->getOperand(0);
1923 SDValue Vec1 = N->getOperand(1);
1924 ResultStack Results(SN);
1925 Results.push(TargetOpcode::COPY, ResTy, {Vec0});
1926 Results.push(TargetOpcode::COPY, ResTy, {Vec1});
1927 OpRef Va = OpRef::res(Results.top()-1);
1928 OpRef Vb = OpRef::res(Results.top());
1929
1930 OpRef Res = !HavePairs ? shuffs2(ShuffleMask(Mask), Va, Vb, Results)
1931 : shuffp2(ShuffleMask(Mask), Va, Vb, Results);
1932
1933 bool Done = Res.isValid();
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001934 if (Done) {
1935 // Make sure that Res is on the stack before materializing.
1936 Results.push(TargetOpcode::COPY, ResTy, {Res});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001937 materialize(Results);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001938 } else {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001939 Done = scalarizeShuffle(Mask, SDLoc(N), ResTy, Vec0, Vec1, N);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001940 }
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001941
1942 if (!Done) {
1943#ifndef NDEBUG
1944 dbgs() << "Unhandled shuffle:\n";
1945 SN->dumpr(&DAG);
1946#endif
1947 llvm_unreachable("Failed to select vector shuffle");
1948 }
1949}
1950
1951void HvxSelector::selectRor(SDNode *N) {
1952 // If this is a rotation by less than 8, use V6_valignbi.
1953 MVT Ty = N->getValueType(0).getSimpleVT();
1954 const SDLoc &dl(N);
1955 SDValue VecV = N->getOperand(0);
1956 SDValue RotV = N->getOperand(1);
1957 SDNode *NewN = nullptr;
1958
1959 if (auto *CN = dyn_cast<ConstantSDNode>(RotV.getNode())) {
1960 unsigned S = CN->getZExtValue();
1961 if (S % HST.getVectorLength() == 0) {
1962 NewN = VecV.getNode();
1963 } else if (isUInt<3>(S)) {
1964 SDValue C = DAG.getTargetConstant(S, dl, MVT::i32);
1965 NewN = DAG.getMachineNode(Hexagon::V6_valignbi, dl, Ty,
1966 {VecV, VecV, C});
1967 }
1968 }
1969
1970 if (!NewN)
1971 NewN = DAG.getMachineNode(Hexagon::V6_vror, dl, Ty, {VecV, RotV});
1972
1973 ISel.ReplaceNode(N, NewN);
1974 DAG.RemoveDeadNode(N);
1975}
1976
1977void HexagonDAGToDAGISel::SelectHvxShuffle(SDNode *N) {
1978 HvxSelector(*this, *CurDAG).selectShuffle(N);
1979}
1980
1981void HexagonDAGToDAGISel::SelectHvxRor(SDNode *N) {
1982 HvxSelector(*this, *CurDAG).selectRor(N);
1983}
1984
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00001985void HexagonDAGToDAGISel::SelectV65GatherPred(SDNode *N) {
1986 const SDLoc &dl(N);
1987 SDValue Chain = N->getOperand(0);
1988 SDValue Address = N->getOperand(2);
1989 SDValue Predicate = N->getOperand(3);
1990 SDValue Base = N->getOperand(4);
1991 SDValue Modifier = N->getOperand(5);
1992 SDValue Offset = N->getOperand(6);
1993
1994 unsigned Opcode;
1995 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
1996 switch (IntNo) {
1997 default:
1998 llvm_unreachable("Unexpected HVX gather intrinsic.");
1999 case Intrinsic::hexagon_V6_vgathermhq:
2000 case Intrinsic::hexagon_V6_vgathermhq_128B:
2001 Opcode = Hexagon::V6_vgathermhq_pseudo;
2002 break;
2003 case Intrinsic::hexagon_V6_vgathermwq:
2004 case Intrinsic::hexagon_V6_vgathermwq_128B:
2005 Opcode = Hexagon::V6_vgathermwq_pseudo;
2006 break;
2007 case Intrinsic::hexagon_V6_vgathermhwq:
2008 case Intrinsic::hexagon_V6_vgathermhwq_128B:
2009 Opcode = Hexagon::V6_vgathermhwq_pseudo;
2010 break;
2011 }
2012
2013 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2014 SDValue Ops[] = { Address, Predicate, Base, Modifier, Offset, Chain };
2015 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2016
2017 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2018 MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2019 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2020
2021 ReplaceUses(N, Result);
2022 CurDAG->RemoveDeadNode(N);
2023}
2024
2025void HexagonDAGToDAGISel::SelectV65Gather(SDNode *N) {
2026 const SDLoc &dl(N);
2027 SDValue Chain = N->getOperand(0);
2028 SDValue Address = N->getOperand(2);
2029 SDValue Base = N->getOperand(3);
2030 SDValue Modifier = N->getOperand(4);
2031 SDValue Offset = N->getOperand(5);
2032
2033 unsigned Opcode;
2034 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2035 switch (IntNo) {
2036 default:
2037 llvm_unreachable("Unexpected HVX gather intrinsic.");
2038 case Intrinsic::hexagon_V6_vgathermh:
2039 case Intrinsic::hexagon_V6_vgathermh_128B:
2040 Opcode = Hexagon::V6_vgathermh_pseudo;
2041 break;
2042 case Intrinsic::hexagon_V6_vgathermw:
2043 case Intrinsic::hexagon_V6_vgathermw_128B:
2044 Opcode = Hexagon::V6_vgathermw_pseudo;
2045 break;
2046 case Intrinsic::hexagon_V6_vgathermhw:
2047 case Intrinsic::hexagon_V6_vgathermhw_128B:
2048 Opcode = Hexagon::V6_vgathermhw_pseudo;
2049 break;
2050 }
2051
2052 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2053 SDValue Ops[] = { Address, Base, Modifier, Offset, Chain };
2054 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2055
2056 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2057 MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2058 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2059
2060 ReplaceUses(N, Result);
2061 CurDAG->RemoveDeadNode(N);
2062}
2063
2064void HexagonDAGToDAGISel::SelectHVXDualOutput(SDNode *N) {
2065 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2066 SDNode *Result;
2067 switch (IID) {
2068 case Intrinsic::hexagon_V6_vaddcarry: {
2069 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2070 N->getOperand(3) };
2071 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2072 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2073 break;
2074 }
2075 case Intrinsic::hexagon_V6_vaddcarry_128B: {
2076 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2077 N->getOperand(3) };
2078 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2079 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2080 break;
2081 }
2082 case Intrinsic::hexagon_V6_vsubcarry: {
2083 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2084 N->getOperand(3) };
2085 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2086 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2087 break;
2088 }
2089 case Intrinsic::hexagon_V6_vsubcarry_128B: {
2090 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2091 N->getOperand(3) };
2092 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2093 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2094 break;
2095 }
2096 default:
2097 llvm_unreachable("Unexpected HVX dual output intrinsic.");
2098 }
2099 ReplaceUses(N, Result);
2100 ReplaceUses(SDValue(N, 0), SDValue(Result, 0));
2101 ReplaceUses(SDValue(N, 1), SDValue(Result, 1));
2102 CurDAG->RemoveDeadNode(N);
2103}
2104
2105