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