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