1 //===-- HexagonISelDAGToDAGHVX.cpp ----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
26 #define DEBUG_TYPE "hexagon-isel"
32 // --------------------------------------------------------------------
33 // Implementation of permutation networks.
35 // Implementation of the node routing through butterfly networks:
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.
48 // [1] Hexagon's vdelta/vrdelta allow an element to be routed to both
49 // positions as long as there is no conflict.
51 // Here's a delta network for 8 inputs, only the switching routes are
55 // |- 1 ---------------|- 2 -----|- 3 -|
57 // Inp[0] *** *** *** *** Out[0]
61 // Inp[1] *** \ / *** X *** *** Out[1]
65 // Inp[2] *** \ \ / / *** X *** *** Out[2]
69 // Inp[3] *** \ / \ / \ / *** *** *** Out[3]
75 // Inp[4] *** / \ / \ / \ *** *** *** Out[4]
79 // Inp[5] *** / / \ \ *** X *** *** Out[5]
83 // Inp[6] *** / \ *** X *** *** Out[6]
87 // Inp[7] *** *** *** *** Out[7]
90 // Reverse delta network is same as delta network, with the steps in
91 // the opposite order.
94 // Benes network is a forward delta network immediately followed by
95 // a reverse delta network.
98 // Graph coloring utility used to partition nodes into two groups:
99 // they will correspond to nodes routed to the upper and lower networks.
108 using MapType = std::map<Node,uint8_t>;
109 static constexpr Node Ignore = Node(-1);
111 Coloring(ArrayRef<Node> Ord) : Order(Ord) {
117 const MapType &colors() const {
121 uint8_t other(uint8_t Color) {
124 return Color == Red ? Black : Red;
130 ArrayRef<Node> Order;
132 std::set<Node> Needed;
134 using NodeSet = std::set<Node>;
135 std::map<Node,NodeSet> Edges;
137 Node conj(Node Pos) {
138 Node Num = Order.size();
139 return (Pos < Num/2) ? Pos + Num/2 : Pos - Num/2;
142 uint8_t getColor(Node N) {
143 auto F = Colors.find(N);
144 return F != Colors.end() ? F->second : (uint8_t)None;
147 std::pair<bool,uint8_t> getUniqueColor(const NodeSet &Nodes);
154 std::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);
162 else if (Color != None && Color != ColorN)
163 return { false, None };
165 return { true, Color };
168 void Coloring::build() {
169 // Add Order[P] and Order[conj(P)] to Edges.
170 for (unsigned P = 0; P != Order.size(); ++P) {
174 Node PC = Order[conj(P)];
175 if (PC != Ignore && PC != I)
179 // Add I and conj(I) to Edges.
180 for (unsigned I = 0; I != Order.size(); ++I) {
181 if (!Needed.count(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];
193 bool Coloring::color() {
194 SetVector<Node> FirstQ;
195 auto Enqueue = [this,&FirstQ] (Node N) {
198 for (unsigned I = 0; I != Q.size(); ++I) {
199 NodeSet &Ns = Edges[Q[I]];
200 Q.insert(Ns.begin(), Ns.end());
202 FirstQ.insert(Q.begin(), Q.end());
204 for (Node N : Needed)
207 for (Node N : FirstQ) {
210 NodeSet &Ns = Edges[N];
211 auto P = getUniqueColor(Ns);
214 Colors[N] = other(P.second);
217 // First, color nodes that don't have any dups.
218 for (auto E : Edges) {
220 if (!Needed.count(conj(N)) || Colors.count(N))
222 auto P = getUniqueColor(E.second);
225 Colors[N] = other(P.second);
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) {
233 if (!Colors.count(N))
237 for (unsigned I = 0; I < WorkQ.size(); ++I) {
239 NodeSet &Ns = Edges[N];
240 auto P = getUniqueColor(Ns);
242 Colors[N] = other(P.second);
246 // Coloring failed. Split this node.
248 uint8_t ColorN = other(None);
249 uint8_t ColorC = other(ColorN);
250 NodeSet &Cs = Edges[C];
252 for (Node M : CopyNs) {
253 uint8_t ColorM = getColor(M);
254 if (ColorM == ColorC) {
255 // Connect M with C, disconnect M from N.
266 // Explicitly assign "None" all all uncolored nodes.
267 for (unsigned I = 0; I != Order.size(); ++I)
268 if (Colors.count(I) == 0)
275 void Coloring::dump() const {
276 dbgs() << "{ Order: {";
277 for (unsigned I = 0; I != Order.size(); ++I) {
285 dbgs() << " Needed: {";
286 for (Node N : Needed)
290 dbgs() << " Edges: {\n";
291 for (auto E : Edges) {
292 dbgs() << " " << E.first << " -> {";
293 for (auto N : E.second)
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";
307 // Base class of for reordering networks. They don't strictly need to be
308 // permutations, as outputs with repeated occurrences of an input element
311 using Controls = std::vector<uint8_t>;
312 using ElemType = int;
313 static constexpr ElemType Ignore = ElemType(-1);
325 PermNetwork(ArrayRef<ElemType> Ord, unsigned Mult = 1) {
326 Order.assign(Ord.data(), Ord.data()+Ord.size());
329 unsigned S = Order.size();
333 Table.resize(Order.size());
334 for (RowType &Row : Table)
335 Row.resize(Mult*Log, None);
338 void getControls(Controls &V, unsigned StartAt, uint8_t Dir) const {
339 unsigned Size = Order.size();
341 for (unsigned I = 0; I != Size; ++I) {
343 for (unsigned L = 0; L != Log; ++L) {
344 unsigned C = ctl(I, StartAt+L) == Switch;
350 assert(isUInt<8>(W));
355 uint8_t ctl(ElemType Pos, unsigned Step) const {
356 return Table[Pos][Step];
358 unsigned size() const {
361 unsigned steps() const {
367 std::vector<ElemType> Order;
368 using RowType = std::vector<uint8_t>;
369 std::vector<RowType> Table;
372 struct ForwardDeltaNetwork : public PermNetwork {
373 ForwardDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
375 bool run(Controls &V) {
376 if (!route(Order.data(), Table.data(), size(), 0))
378 getControls(V, 0, Forward);
383 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
386 struct ReverseDeltaNetwork : public PermNetwork {
387 ReverseDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
389 bool run(Controls &V) {
390 if (!route(Order.data(), Table.data(), size(), 0))
392 getControls(V, 0, Reverse);
397 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
400 struct BenesNetwork : public PermNetwork {
401 BenesNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord, 2) {}
403 bool run(Controls &F, Controls &R) {
404 if (!route(Order.data(), Table.data(), size(), 0))
407 getControls(F, 0, Forward);
408 getControls(R, Log, Reverse);
413 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
417 bool ForwardDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
419 bool UseUp = false, UseDown = false;
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) {
428 // I is the position in the input,
429 // J is the position in the output.
434 S = (J < Num/2) ? Pass : Switch;
436 S = (J < Num/2) ? Switch : Pass;
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);
444 if (T[U][Step] != S && T[U][Step] != None)
449 for (ElemType J = 0; J != Num; ++J)
450 if (P[J] != Ignore && P[J] >= Num/2)
454 if (UseUp && !route(P, T, Size/2, Step+1))
456 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
462 bool ReverseDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
464 unsigned Pets = Log-1 - Step;
465 bool UseUp = false, UseDown = false;
468 // In this step half-switching occurs, so coloring can be used.
469 Coloring G({P,Size});
470 const Coloring::MapType &M = G.colors();
474 uint8_t ColorUp = Coloring::None;
475 for (ElemType J = 0; J != Num; ++J) {
477 // I is the position in the input,
478 // J is the position in the output.
482 if (C == Coloring::None)
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.
497 S = (J < Num/2) ? Pass : Switch;
500 S = (J < Num/2) ? Switch : Pass;
506 // Reorder the working permutation according to the computed switch table
507 // for the last step (i.e. Pets).
508 for (ElemType J = 0, E = Size / 2; J != E; ++J) {
509 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)
515 if (T[J+Size/2][Pets] == Switch)
521 for (ElemType J = 0; J != Num; ++J)
522 if (P[J] != Ignore && P[J] >= Num/2)
526 if (UseUp && !route(P, T, Size/2, Step+1))
528 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
534 bool BenesNetwork::route(ElemType *P, RowType *T, unsigned Size,
536 Coloring G({P,Size});
537 const Coloring::MapType &M = G.colors();
542 unsigned Pets = 2*Log-1 - Step;
543 bool UseUp = false, UseDown = false;
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) {
554 if (C == Coloring::None)
556 if (ColorUp == Coloring::None) {
557 ColorUp = (I < Num/2) ? Coloring::Red : Coloring::Black;
559 unsigned CI = (I < Num/2) ? I+Num/2 : I-Num/2;
564 T[CI][Step] = Switch;
565 T[J][Pets] = (J < Num/2) ? Pass : Switch;
569 T[CI][Step] = Switch;
572 T[J][Pets] = (J < Num/2) ? Switch : Pass;
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)
586 if (T[J+Num/2][Pets] == Switch)
592 for (ElemType J = 0; J != Num; ++J)
593 if (P[J] != Ignore && P[J] >= Num/2)
597 if (UseUp && !route(P, T, Size/2, Step+1))
599 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
605 // --------------------------------------------------------------------
606 // Support for building selection results (output instructions that are
607 // parts of the final selection).
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); }
617 static OpRef lo(const OpRef &R) {
618 assert(!R.isValue());
619 return OpRef(R.OpN & (Undef | Index | LoHalf));
621 static OpRef hi(const OpRef &R) {
622 assert(!R.isValue());
623 return OpRef(R.OpN & (Undef | Index | HiHalf));
625 static OpRef undef(MVT Ty) { return OpRef(Undef | Ty.SimpleTy); }
628 SDValue OpV = SDValue();
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
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.
638 Invalid = 0x10000000,
641 Whole = LoHalf | HiHalf,
643 Index = 0x0FFFFFFF, // Mask of the index value.
647 void print(raw_ostream &OS, const SelectionDAG &G) const;
650 OpRef(unsigned N) : OpN(N) {}
653 struct NodeTemplate {
654 NodeTemplate() = default;
657 std::vector<OpRef> Ops;
659 void print(raw_ostream &OS, const SelectionDAG &G) const;
663 ResultStack(SDNode *Inp)
664 : InpNode(Inp), InpTy(Inp->getValueType(0).getSimpleVT()) {}
667 unsigned push(const NodeTemplate &Res) {
669 return List.size()-1;
671 unsigned push(unsigned Opc, MVT Ty, std::vector<OpRef> &&Ops) {
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);
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(); }
695 void print(raw_ostream &OS, const SelectionDAG &G) const;
699 void OpRef::print(raw_ostream &OS, const SelectionDAG &G) const {
701 OpV.getNode()->print(OS, &G);
712 if ((OpN & Whole) != Whole) {
713 assert((OpN & Whole) == LoHalf || (OpN & Whole) == HiHalf);
719 OS << '#' << SignExtend32(OpN & Index, IndexBits);
722 void 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()) << " "
727 for (const auto &R : Ops) {
736 void ResultStack::print(raw_ostream &OS, const SelectionDAG &G) const {
737 OS << "Input node:\n";
741 OS << "Result templates:\n";
742 for (unsigned I = 0, E = List.size(); I != E; ++I) {
743 OS << '[' << I << "] ";
744 List[I].print(OS, G);
751 ShuffleMask(ArrayRef<int> M) : Mask(M) {
752 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
756 MinSrc = (MinSrc == -1) ? M : std::min(MinSrc, M);
757 MaxSrc = (MaxSrc == -1) ? M : std::max(MaxSrc, M);
762 int MinSrc = -1, MaxSrc = -1;
764 ShuffleMask lo() const {
765 size_t H = Mask.size()/2;
766 return ShuffleMask(Mask.take_front(H));
768 ShuffleMask hi() const {
769 size_t H = Mask.size()/2;
770 return ShuffleMask(Mask.take_back(H));
775 // --------------------------------------------------------------------
776 // The HvxSelector class.
778 static const HexagonTargetLowering &getHexagonLowering(SelectionDAG &G) {
779 return static_cast<const HexagonTargetLowering&>(G.getTargetLoweringInfo());
781 static const HexagonSubtarget &getHexagonSubtarget(SelectionDAG &G) {
782 return static_cast<const HexagonSubtarget&>(G.getSubtarget());
787 const HexagonTargetLowering &Lower;
788 HexagonDAGToDAGISel &ISel;
790 const HexagonSubtarget &HST;
791 const unsigned HwLen;
793 HvxSelector(HexagonDAGToDAGISel &HS, SelectionDAG &G)
794 : Lower(getHexagonLowering(G)), ISel(HS), DAG(G),
795 HST(getHexagonSubtarget(G)), HwLen(HST.getVectorLength()) {}
797 MVT getSingleVT(MVT ElemTy) const {
798 unsigned NumElems = HwLen / (ElemTy.getSizeInBits()/8);
799 return MVT::getVectorVT(ElemTy, NumElems);
802 MVT getPairVT(MVT ElemTy) const {
803 unsigned NumElems = (2*HwLen) / (ElemTy.getSizeInBits()/8);
804 return MVT::getVectorVT(ElemTy, NumElems);
807 void selectShuffle(SDNode *N);
808 void selectRor(SDNode *N);
811 void materialize(const ResultStack &Results);
813 SDValue getVectorConstant(ArrayRef<uint8_t> Data, const SDLoc &dl);
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 vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
825 ResultStack &Results);
826 OpRef vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
827 ResultStack &Results);
829 OpRef shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results);
830 OpRef shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
831 OpRef shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results);
832 OpRef shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
834 OpRef butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results);
835 OpRef contracting(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
836 OpRef expanding(ShuffleMask SM, OpRef Va, ResultStack &Results);
837 OpRef perfect(ShuffleMask SM, OpRef Va, ResultStack &Results);
839 bool selectVectorConstants(SDNode *N);
840 bool scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl, MVT ResTy,
841 SDValue Va, SDValue Vb, SDNode *N);
846 static void splitMask(ArrayRef<int> Mask, MutableArrayRef<int> MaskL,
847 MutableArrayRef<int> MaskR) {
848 unsigned VecLen = Mask.size();
849 assert(MaskL.size() == VecLen && MaskR.size() == VecLen);
850 for (unsigned I = 0; I != VecLen; ++I) {
853 MaskL[I] = MaskR[I] = -1;
854 } else if (unsigned(M) < VecLen) {
864 static std::pair<int,unsigned> findStrip(ArrayRef<int> A, int Inc,
866 assert(A.size() > 0 && A.size() >= MaxLen);
869 for (unsigned I = 1; I != MaxLen; ++I) {
874 return { F, MaxLen };
877 static bool isUndef(ArrayRef<int> Mask) {
884 static bool isIdentity(ArrayRef<int> Mask) {
885 for (int I = 0, E = Mask.size(); I != E; ++I) {
887 if (M >= 0 && M != I)
893 static bool isPermutation(ArrayRef<int> Mask) {
894 // Check by adding all numbers only works if there is no overflow.
895 assert(Mask.size() < 0x00007FFF && "Sanity failure");
897 for (int Idx : Mask) {
903 return 2*Sum == N*(N-1);
906 bool HvxSelector::selectVectorConstants(SDNode *N) {
907 // Constant vectors are generated as loads from constant pools.
908 // Since they are generated during the selection process, the main
909 // selection algorithm is not aware of them. Select them directly
911 SmallVector<SDNode*,4> Loads;
912 SmallVector<SDNode*,16> WorkQ;
914 // The DAG can change (due to CSE) during selection, so cache all the
915 // unselected nodes first to avoid traversing a mutating DAG.
917 auto IsLoadToSelect = [] (SDNode *N) {
918 if (!N->isMachineOpcode() && N->getOpcode() == ISD::LOAD) {
919 SDValue Addr = cast<LoadSDNode>(N)->getBasePtr();
920 unsigned AddrOpc = Addr.getOpcode();
921 if (AddrOpc == HexagonISD::AT_PCREL || AddrOpc == HexagonISD::CP)
922 if (Addr.getOperand(0).getOpcode() == ISD::TargetConstantPool)
929 for (unsigned i = 0; i != WorkQ.size(); ++i) {
930 SDNode *W = WorkQ[i];
931 if (IsLoadToSelect(W)) {
935 for (unsigned j = 0, f = W->getNumOperands(); j != f; ++j)
936 WorkQ.push_back(W->getOperand(j).getNode());
939 for (SDNode *L : Loads)
942 return !Loads.empty();
945 void HvxSelector::materialize(const ResultStack &Results) {
946 DEBUG_WITH_TYPE("isel", {
947 dbgs() << "Materializing\n";
948 Results.print(dbgs(), DAG);
952 const SDLoc &dl(Results.InpNode);
953 std::vector<SDValue> Output;
955 for (unsigned I = 0, E = Results.size(); I != E; ++I) {
956 const NodeTemplate &Node = Results[I];
957 std::vector<SDValue> Ops;
958 for (const OpRef &R : Node.Ops) {
961 Ops.push_back(R.OpV);
964 if (R.OpN & OpRef::Undef) {
965 MVT::SimpleValueType SVT = MVT::SimpleValueType(R.OpN & OpRef::Index);
966 Ops.push_back(ISel.selectUndef(dl, MVT(SVT)));
969 // R is an index of a result.
970 unsigned Part = R.OpN & OpRef::Whole;
971 int Idx = SignExtend32(R.OpN & OpRef::Index, OpRef::IndexBits);
974 assert(Idx >= 0 && unsigned(Idx) < Output.size());
975 SDValue Op = Output[Idx];
976 MVT OpTy = Op.getValueType().getSimpleVT();
977 if (Part != OpRef::Whole) {
978 assert(Part == OpRef::LoHalf || Part == OpRef::HiHalf);
979 if (Op.getOpcode() == HexagonISD::VCOMBINE) {
980 Op = (Part == OpRef::HiHalf) ? Op.getOperand(0) : Op.getOperand(1);
982 MVT HalfTy = MVT::getVectorVT(OpTy.getVectorElementType(),
983 OpTy.getVectorNumElements()/2);
984 unsigned Sub = (Part == OpRef::LoHalf) ? Hexagon::vsub_lo
986 Op = DAG.getTargetExtractSubreg(Sub, dl, HalfTy, Op);
990 } // for (Node : Results)
992 assert(Node.Ty != MVT::Other);
993 SDNode *ResN = (Node.Opc == TargetOpcode::COPY)
994 ? Ops.front().getNode()
995 : DAG.getMachineNode(Node.Opc, dl, Node.Ty, Ops);
996 Output.push_back(SDValue(ResN, 0));
999 SDNode *OutN = Output.back().getNode();
1000 SDNode *InpN = Results.InpNode;
1001 DEBUG_WITH_TYPE("isel", {
1002 dbgs() << "Generated node:\n";
1006 ISel.ReplaceNode(InpN, OutN);
1007 selectVectorConstants(OutN);
1008 DAG.RemoveDeadNodes();
1011 OpRef HvxSelector::concat(OpRef Lo, OpRef Hi, ResultStack &Results) {
1012 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1013 const SDLoc &dl(Results.InpNode);
1014 Results.push(TargetOpcode::REG_SEQUENCE, getPairVT(MVT::i8), {
1015 DAG.getTargetConstant(Hexagon::HvxWRRegClassID, dl, MVT::i32),
1016 Lo, DAG.getTargetConstant(Hexagon::vsub_lo, dl, MVT::i32),
1017 Hi, DAG.getTargetConstant(Hexagon::vsub_hi, dl, MVT::i32),
1019 return OpRef::res(Results.top());
1022 // Va, Vb are single vectors, SM can be arbitrarily long.
1023 OpRef HvxSelector::packs(ShuffleMask SM, OpRef Va, OpRef Vb,
1024 ResultStack &Results, MutableArrayRef<int> NewMask,
1026 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1027 if (!Va.isValid() || !Vb.isValid())
1028 return OpRef::fail();
1030 int VecLen = SM.Mask.size();
1031 MVT Ty = getSingleVT(MVT::i8);
1033 if (SM.MaxSrc - SM.MinSrc < int(HwLen)) {
1034 if (SM.MaxSrc < int(HwLen)) {
1035 memcpy(NewMask.data(), SM.Mask.data(), sizeof(int)*VecLen);
1038 if (SM.MinSrc >= int(HwLen)) {
1039 for (int I = 0; I != VecLen; ++I) {
1047 const SDLoc &dl(Results.InpNode);
1048 SDValue S = DAG.getTargetConstant(SM.MinSrc, dl, MVT::i32);
1049 if (isUInt<3>(SM.MinSrc)) {
1050 Results.push(Hexagon::V6_valignbi, Ty, {Vb, Va, S});
1052 Results.push(Hexagon::A2_tfrsi, MVT::i32, {S});
1053 unsigned Top = Results.top();
1054 Results.push(Hexagon::V6_valignb, Ty, {Vb, Va, OpRef::res(Top)});
1056 for (int I = 0; I != VecLen; ++I) {
1062 return OpRef::res(Results.top());
1065 if (Options & PackMux) {
1066 // If elements picked from Va and Vb have all different (source) indexes
1067 // (relative to the start of the argument), do a mux, and update the mask.
1068 BitVector Picked(HwLen);
1069 SmallVector<uint8_t,128> MuxBytes(HwLen);
1071 for (int I = 0; I != VecLen; ++I) {
1075 if (M >= int(HwLen))
1086 return vmuxs(MuxBytes, Va, Vb, Results);
1089 return OpRef::fail();
1092 OpRef HvxSelector::packp(ShuffleMask SM, OpRef Va, OpRef Vb,
1093 ResultStack &Results, MutableArrayRef<int> NewMask) {
1094 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1095 unsigned HalfMask = 0;
1096 unsigned LogHw = Log2_32(HwLen);
1097 for (int M : SM.Mask) {
1100 HalfMask |= (1u << (M >> LogHw));
1104 return OpRef::undef(getPairVT(MVT::i8));
1106 // If more than two halves are used, bail.
1107 // TODO: be more aggressive here?
1108 if (countPopulation(HalfMask) > 2)
1109 return OpRef::fail();
1111 MVT HalfTy = getSingleVT(MVT::i8);
1113 OpRef Inp[2] = { Va, Vb };
1114 OpRef Out[2] = { OpRef::undef(HalfTy), OpRef::undef(HalfTy) };
1116 uint8_t HalfIdx[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
1118 for (unsigned I = 0; I != 4; ++I) {
1119 if ((HalfMask & (1u << I)) == 0)
1122 OpRef Op = Inp[I/2];
1123 Out[Idx] = (I & 1) ? OpRef::hi(Op) : OpRef::lo(Op);
1127 int VecLen = SM.Mask.size();
1128 for (int I = 0; I != VecLen; ++I) {
1131 uint8_t Idx = HalfIdx[M >> LogHw];
1132 assert(Idx == 0 || Idx == 1);
1133 M = (M & (HwLen-1)) + HwLen*Idx;
1138 return concat(Out[0], Out[1], Results);
1141 OpRef HvxSelector::vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1142 ResultStack &Results) {
1143 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1144 MVT ByteTy = getSingleVT(MVT::i8);
1145 MVT BoolTy = MVT::getVectorVT(MVT::i1, 8*HwLen); // XXX
1146 const SDLoc &dl(Results.InpNode);
1147 SDValue B = getVectorConstant(Bytes, dl);
1148 Results.push(Hexagon::V6_vd0, ByteTy, {});
1149 Results.push(Hexagon::V6_veqb, BoolTy, {OpRef(B), OpRef::res(-1)});
1150 Results.push(Hexagon::V6_vmux, ByteTy, {OpRef::res(-1), Vb, Va});
1151 return OpRef::res(Results.top());
1154 OpRef HvxSelector::vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1155 ResultStack &Results) {
1156 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1157 size_t S = Bytes.size() / 2;
1158 OpRef L = vmuxs(Bytes.take_front(S), OpRef::lo(Va), OpRef::lo(Vb), Results);
1159 OpRef H = vmuxs(Bytes.drop_front(S), OpRef::hi(Va), OpRef::hi(Vb), Results);
1160 return concat(L, H, Results);
1163 OpRef HvxSelector::shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1164 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1165 unsigned VecLen = SM.Mask.size();
1166 assert(HwLen == VecLen);
1168 assert(all_of(SM.Mask, [this](int M) { return M == -1 || M < int(HwLen); }));
1170 if (isIdentity(SM.Mask))
1172 if (isUndef(SM.Mask))
1173 return OpRef::undef(getSingleVT(MVT::i8));
1175 OpRef P = perfect(SM, Va, Results);
1178 return butterfly(SM, Va, Results);
1181 OpRef HvxSelector::shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb,
1182 ResultStack &Results) {
1183 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1184 if (isUndef(SM.Mask))
1185 return OpRef::undef(getSingleVT(MVT::i8));
1187 OpRef C = contracting(SM, Va, Vb, Results);
1191 int VecLen = SM.Mask.size();
1192 SmallVector<int,128> NewMask(VecLen);
1193 OpRef P = packs(SM, Va, Vb, Results, NewMask);
1195 return shuffs1(ShuffleMask(NewMask), P, Results);
1197 SmallVector<int,128> MaskL(VecLen), MaskR(VecLen);
1198 splitMask(SM.Mask, MaskL, MaskR);
1200 OpRef L = shuffs1(ShuffleMask(MaskL), Va, Results);
1201 OpRef R = shuffs1(ShuffleMask(MaskR), Vb, Results);
1202 if (!L.isValid() || !R.isValid())
1203 return OpRef::fail();
1205 SmallVector<uint8_t,128> Bytes(VecLen);
1206 for (int I = 0; I != VecLen; ++I) {
1210 return vmuxs(Bytes, L, R, Results);
1213 OpRef HvxSelector::shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1214 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1215 int VecLen = SM.Mask.size();
1217 if (isIdentity(SM.Mask))
1219 if (isUndef(SM.Mask))
1220 return OpRef::undef(getPairVT(MVT::i8));
1222 SmallVector<int,128> PackedMask(VecLen);
1223 OpRef P = packs(SM, OpRef::lo(Va), OpRef::hi(Va), Results, PackedMask);
1225 ShuffleMask PM(PackedMask);
1226 OpRef E = expanding(PM, P, Results);
1230 OpRef L = shuffs1(PM.lo(), P, Results);
1231 OpRef H = shuffs1(PM.hi(), P, Results);
1232 if (L.isValid() && H.isValid())
1233 return concat(L, H, Results);
1236 OpRef R = perfect(SM, Va, Results);
1239 // TODO commute the mask and try the opposite order of the halves.
1241 OpRef L = shuffs2(SM.lo(), OpRef::lo(Va), OpRef::hi(Va), Results);
1242 OpRef H = shuffs2(SM.hi(), OpRef::lo(Va), OpRef::hi(Va), Results);
1243 if (L.isValid() && H.isValid())
1244 return concat(L, H, Results);
1246 return OpRef::fail();
1249 OpRef HvxSelector::shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb,
1250 ResultStack &Results) {
1251 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1252 if (isUndef(SM.Mask))
1253 return OpRef::undef(getPairVT(MVT::i8));
1255 int VecLen = SM.Mask.size();
1256 SmallVector<int,256> PackedMask(VecLen);
1257 OpRef P = packp(SM, Va, Vb, Results, PackedMask);
1259 return shuffp1(ShuffleMask(PackedMask), P, Results);
1261 SmallVector<int,256> MaskL(VecLen), MaskR(VecLen);
1262 OpRef L = shuffp1(ShuffleMask(MaskL), Va, Results);
1263 OpRef R = shuffp1(ShuffleMask(MaskR), Vb, Results);
1264 if (!L.isValid() || !R.isValid())
1265 return OpRef::fail();
1268 SmallVector<uint8_t,256> Bytes(VecLen);
1269 for (int I = 0; I != VecLen; ++I) {
1273 return vmuxp(Bytes, L, R, Results);
1276 bool HvxSelector::scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl,
1277 MVT ResTy, SDValue Va, SDValue Vb,
1279 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1280 MVT ElemTy = ResTy.getVectorElementType();
1281 assert(ElemTy == MVT::i8);
1282 unsigned VecLen = Mask.size();
1283 bool HavePairs = (2*HwLen == VecLen);
1284 MVT SingleTy = getSingleVT(MVT::i8);
1286 SmallVector<SDValue,128> Ops;
1287 for (int I : Mask) {
1289 Ops.push_back(ISel.selectUndef(dl, ElemTy));
1302 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, SingleTy, Vec);
1304 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, SingleTy, Vec);
1308 SDValue Idx = DAG.getConstant(M, dl, MVT::i32);
1309 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ElemTy, {Vec, Idx});
1310 SDValue L = Lower.LowerOperation(Ex, DAG);
1311 assert(L.getNode());
1316 if (2*HwLen == VecLen) {
1317 SDValue B0 = DAG.getBuildVector(SingleTy, dl, {Ops.data(), HwLen});
1318 SDValue L0 = Lower.LowerOperation(B0, DAG);
1319 SDValue B1 = DAG.getBuildVector(SingleTy, dl, {Ops.data()+HwLen, HwLen});
1320 SDValue L1 = Lower.LowerOperation(B1, DAG);
1321 // XXX CONCAT_VECTORS is legal for HVX vectors. Legalizing (lowering)
1322 // functions may expect to be called only for illegal operations, so
1323 // make sure that they are not called for legal ones. Develop a better
1324 // mechanism for dealing with this.
1325 LV = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, {L0, L1});
1327 SDValue BV = DAG.getBuildVector(ResTy, dl, Ops);
1328 LV = Lower.LowerOperation(BV, DAG);
1331 assert(!N->use_empty());
1332 ISel.ReplaceNode(N, LV.getNode());
1333 DAG.RemoveDeadNodes();
1335 std::deque<SDNode*> SubNodes;
1336 SubNodes.push_back(LV.getNode());
1337 for (unsigned I = 0; I != SubNodes.size(); ++I) {
1338 for (SDValue Op : SubNodes[I]->ops())
1339 SubNodes.push_back(Op.getNode());
1341 while (!SubNodes.empty()) {
1342 SDNode *S = SubNodes.front();
1343 SubNodes.pop_front();
1346 // This isn't great, but users need to be selected before any nodes that
1347 // they use. (The reason is to match larger patterns, and avoid nodes that
1348 // cannot be matched on their own, e.g. ValueType, TokenFactor, etc.).
1349 bool PendingUser = llvm::any_of(S->uses(), [&SubNodes](const SDNode *U) {
1350 return llvm::any_of(SubNodes, [U](const SDNode *T) {
1355 SubNodes.push_back(S);
1360 DAG.RemoveDeadNodes();
1364 OpRef HvxSelector::contracting(ShuffleMask SM, OpRef Va, OpRef Vb,
1365 ResultStack &Results) {
1366 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1367 if (!Va.isValid() || !Vb.isValid())
1368 return OpRef::fail();
1370 // Contracting shuffles, i.e. instructions that always discard some bytes
1371 // from the operand vectors.
1375 // V6_vpack{e,o}{b,h}
1377 int VecLen = SM.Mask.size();
1378 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1379 MVT ResTy = getSingleVT(MVT::i8);
1381 // The following shuffles only work for bytes and halfwords. This requires
1382 // the strip length to be 1 or 2.
1383 if (Strip.second != 1 && Strip.second != 2)
1384 return OpRef::fail();
1386 // The patterns for the shuffles, in terms of the starting offsets of the
1387 // consecutive strips (L = length of the strip, N = VecLen):
1389 // vpacke: 0, 2L, 4L ... N+0, N+2L, N+4L ... L = 1 or 2
1390 // vpacko: L, 3L, 5L ... N+L, N+3L, N+5L ... L = 1 or 2
1392 // vshuffe: 0, N+0, 2L, N+2L, 4L ... L = 1 or 2
1393 // vshuffo: L, N+L, 3L, N+3L, 5L ... L = 1 or 2
1395 // vdealb4w: 0, 4, 8 ... 2, 6, 10 ... N+0, N+4, N+8 ... N+2, N+6, N+10 ...
1397 // The value of the element in the mask following the strip will decide
1398 // what kind of a shuffle this can be.
1399 int NextInMask = SM.Mask[Strip.second];
1401 // Check if NextInMask could be 2L, 3L or 4, i.e. if it could be a mask
1402 // for vpack or vdealb4w. VecLen > 4, so NextInMask for vdealb4w would
1404 if (NextInMask < VecLen) {
1405 // vpack{e,o} or vdealb4w
1406 if (Strip.first == 0 && Strip.second == 1 && NextInMask == 4) {
1408 // Check if this is vdealb4w (L=1).
1409 for (int I = 0; I != N/4; ++I)
1410 if (SM.Mask[I] != 4*I)
1411 return OpRef::fail();
1412 for (int I = 0; I != N/4; ++I)
1413 if (SM.Mask[I+N/4] != 2 + 4*I)
1414 return OpRef::fail();
1415 for (int I = 0; I != N/4; ++I)
1416 if (SM.Mask[I+N/2] != N + 4*I)
1417 return OpRef::fail();
1418 for (int I = 0; I != N/4; ++I)
1419 if (SM.Mask[I+3*N/4] != N+2 + 4*I)
1420 return OpRef::fail();
1421 // Matched mask for vdealb4w.
1422 Results.push(Hexagon::V6_vdealb4w, ResTy, {Vb, Va});
1423 return OpRef::res(Results.top());
1426 // Check if this is vpack{e,o}.
1428 int L = Strip.second;
1429 // Check if the first strip starts at 0 or at L.
1430 if (Strip.first != 0 && Strip.first != L)
1431 return OpRef::fail();
1432 // Examine the rest of the mask.
1433 for (int I = L; I < N; I += L) {
1434 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
1435 // Check whether the mask element at the beginning of each strip
1436 // increases by 2L each time.
1437 if (S.first - Strip.first != 2*I)
1438 return OpRef::fail();
1439 // Check whether each strip is of the same length.
1440 if (S.second != unsigned(L))
1441 return OpRef::fail();
1444 // Strip.first == 0 => vpacke
1445 // Strip.first == L => vpacko
1446 assert(Strip.first == 0 || Strip.first == L);
1447 using namespace Hexagon;
1449 Res.Opc = Strip.second == 1 // Number of bytes.
1450 ? (Strip.first == 0 ? V6_vpackeb : V6_vpackob)
1451 : (Strip.first == 0 ? V6_vpackeh : V6_vpackoh);
1453 Res.Ops = { Vb, Va };
1455 return OpRef::res(Results.top());
1458 // Check if this is vshuff{e,o}.
1460 int L = Strip.second;
1461 std::pair<int,unsigned> PrevS = Strip;
1463 for (int I = L; I < N; I += L) {
1464 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
1465 if (S.second != PrevS.second)
1466 return OpRef::fail();
1467 int Diff = Flip ? PrevS.first - S.first + 2*L
1468 : S.first - PrevS.first;
1470 return OpRef::fail();
1474 // Strip.first == 0 => vshuffe
1475 // Strip.first == L => vshuffo
1476 assert(Strip.first == 0 || Strip.first == L);
1477 using namespace Hexagon;
1479 Res.Opc = Strip.second == 1 // Number of bytes.
1480 ? (Strip.first == 0 ? V6_vshuffeb : V6_vshuffob)
1481 : (Strip.first == 0 ? V6_vshufeh : V6_vshufoh);
1483 Res.Ops = { Vb, Va };
1485 return OpRef::res(Results.top());
1488 OpRef HvxSelector::expanding(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1489 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1490 // Expanding shuffles (using all elements and inserting into larger vector):
1492 // V6_vunpacku{b,h} [*]
1494 // [*] Only if the upper elements (filled with 0s) are "don't care" in Mask.
1496 // Note: V6_vunpacko{b,h} are or-ing the high byte/half in the result, so
1497 // they are not shuffles.
1499 // The argument is a single vector.
1501 int VecLen = SM.Mask.size();
1502 assert(2*HwLen == unsigned(VecLen) && "Expecting vector-pair type");
1504 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1506 // The patterns for the unpacks, in terms of the starting offsets of the
1507 // consecutive strips (L = length of the strip, N = VecLen):
1509 // vunpacku: 0, -1, L, -1, 2L, -1 ...
1511 if (Strip.first != 0)
1512 return OpRef::fail();
1514 // The vunpackus only handle byte and half-word.
1515 if (Strip.second != 1 && Strip.second != 2)
1516 return OpRef::fail();
1519 int L = Strip.second;
1521 // First, check the non-ignored strips.
1522 for (int I = 2*L; I < 2*N; I += 2*L) {
1523 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
1524 if (S.second != unsigned(L))
1525 return OpRef::fail();
1527 return OpRef::fail();
1530 for (int I = L; I < 2*N; I += 2*L) {
1531 auto S = findStrip(SM.Mask.drop_front(I), 0, N-I);
1532 if (S.first != -1 || S.second != unsigned(L))
1533 return OpRef::fail();
1536 unsigned Opc = Strip.second == 1 ? Hexagon::V6_vunpackub
1537 : Hexagon::V6_vunpackuh;
1538 Results.push(Opc, getPairVT(MVT::i8), {Va});
1539 return OpRef::res(Results.top());
1542 OpRef HvxSelector::perfect(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1543 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1547 // V6_vshufoe{b,h} those are quivalent to vshuffvdd(..,{1,2})
1548 // V6_vshuffvdd (V6_vshuff)
1549 // V6_dealvdd (V6_vdeal)
1551 int VecLen = SM.Mask.size();
1552 assert(isPowerOf2_32(VecLen) && Log2_32(VecLen) <= 8);
1553 unsigned LogLen = Log2_32(VecLen);
1554 unsigned HwLog = Log2_32(HwLen);
1555 // The result length must be the same as the length of a single vector,
1556 // or a vector pair.
1557 assert(LogLen == HwLog || LogLen == HwLog+1);
1558 bool Extend = (LogLen == HwLog);
1560 if (!isPermutation(SM.Mask))
1561 return OpRef::fail();
1563 SmallVector<unsigned,8> Perm(LogLen);
1565 // Check if this could be a perfect shuffle, or a combination of perfect
1568 // Consider this permutation (using hex digits to make the ASCII diagrams
1570 // { 0, 8, 1, 9, 2, A, 3, B, 4, C, 5, D, 6, E, 7, F }.
1571 // This is a "deal" operation: divide the input into two halves, and
1572 // create the output by picking elements by alternating between these two
1574 // 0 1 2 3 4 5 6 7 --> 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F [*]
1577 // Aside from a few special explicit cases (V6_vdealb, etc.), HVX provides
1578 // a somwehat different mechanism that could be used to perform shuffle/
1579 // deal operations: a 2x2 transpose.
1580 // Consider the halves of inputs again, they can be interpreted as a 2x8
1581 // matrix. A 2x8 matrix can be looked at four 2x2 matrices concatenated
1582 // together. Now, when considering 2 elements at a time, it will be a 2x4
1583 // matrix (with elements 01, 23, 45, etc.), or two 2x2 matrices:
1586 // With groups of 4, this will become a single 2x2 matrix, and so on.
1588 // The 2x2 transpose instruction works by transposing each of the 2x2
1589 // matrices (or "sub-matrices"), given a specific group size. For example,
1590 // if the group size is 1 (i.e. each element is its own group), there
1591 // will be four transposes of the four 2x2 matrices that form the 2x8.
1592 // For example, with the inputs as above, the result will be:
1595 // Now, this result can be tranposed again, but with the group size of 2:
1598 // If we then transpose that result, but with the group size of 4, we get:
1601 // If we concatenate these two rows, it will be
1602 // 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F
1603 // which is the same as the "deal" [*] above.
1605 // In general, a "deal" of individual elements is a series of 2x2 transposes,
1606 // with changing group size. HVX has two instructions:
1607 // Vdd = V6_vdealvdd Vu, Vv, Rt
1608 // Vdd = V6_shufvdd Vu, Vv, Rt
1609 // that perform exactly that. The register Rt controls which transposes are
1610 // going to happen: a bit at position n (counting from 0) indicates that a
1611 // transpose with a group size of 2^n will take place. If multiple bits are
1612 // set, multiple transposes will happen: vdealvdd will perform them starting
1613 // with the largest group size, vshuffvdd will do them in the reverse order.
1615 // The main observation is that each 2x2 transpose corresponds to swapping
1616 // columns of bits in the binary representation of the values.
1618 // The numbers {3,2,1,0} and the log2 of the number of contiguous 1 bits
1619 // in a given column. The * denote the columns that will be swapped.
1620 // The transpose with the group size 2^n corresponds to swapping columns
1621 // 3 (the highest log) and log2(n):
1623 // 3 2 1 0 0 2 1 3 0 2 3 1
1625 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1626 // 1 0 0 0 1 8 1 0 0 0 8 1 0 0 0 8 1 0 0 0
1627 // 2 0 0 1 0 2 0 0 1 0 1 0 0 0 1 1 0 0 0 1
1628 // 3 0 0 1 1 A 1 0 1 0 9 1 0 0 1 9 1 0 0 1
1629 // 4 0 1 0 0 4 0 1 0 0 4 0 1 0 0 2 0 0 1 0
1630 // 5 0 1 0 1 C 1 1 0 0 C 1 1 0 0 A 1 0 1 0
1631 // 6 0 1 1 0 6 0 1 1 0 5 0 1 0 1 3 0 0 1 1
1632 // 7 0 1 1 1 E 1 1 1 0 D 1 1 0 1 B 1 0 1 1
1633 // 8 1 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 1 0 0
1634 // 9 1 0 0 1 9 1 0 0 1 A 1 0 1 0 C 1 1 0 0
1635 // A 1 0 1 0 3 0 0 1 1 3 0 0 1 1 5 0 1 0 1
1636 // B 1 0 1 1 B 1 0 1 1 B 1 0 1 1 D 1 1 0 1
1637 // C 1 1 0 0 5 0 1 0 1 6 0 1 1 0 6 0 1 1 0
1638 // D 1 1 0 1 D 1 1 0 1 E 1 1 1 0 E 1 1 1 0
1639 // E 1 1 1 0 7 0 1 1 1 7 0 1 1 1 7 0 1 1 1
1640 // F 1 1 1 1 F 1 1 1 1 F 1 1 1 1 F 1 1 1 1
1642 auto XorPow2 = [] (ArrayRef<int> Mask, unsigned Num) {
1643 unsigned X = Mask[0] ^ Mask[Num/2];
1644 // Check that the first half has the X's bits clear.
1645 if ((Mask[0] & X) != 0)
1647 for (unsigned I = 1; I != Num/2; ++I) {
1648 if (unsigned(Mask[I] ^ Mask[I+Num/2]) != X)
1650 if ((Mask[I] & X) != 0)
1656 // Create a vector of log2's for each column: Perm[i] corresponds to
1657 // the i-th bit (lsb is 0).
1659 for (unsigned I = VecLen; I >= 2; I >>= 1) {
1660 // Examine the initial segment of Mask of size I.
1661 unsigned X = XorPow2(SM.Mask, I);
1662 if (!isPowerOf2_32(X))
1663 return OpRef::fail();
1664 // Check the other segments of Mask.
1665 for (int J = I; J < VecLen; J += I) {
1666 if (XorPow2(SM.Mask.slice(J, I), I) != X)
1667 return OpRef::fail();
1669 Perm[Log2_32(X)] = Log2_32(I)-1;
1672 // Once we have Perm, represent it as cycles. Denote the maximum log2
1673 // (equal to log2(VecLen)-1) as M. The cycle containing M can then be
1674 // written as (M a1 a2 a3 ... an). That cycle can be broken up into
1675 // simple swaps as (M a1)(M a2)(M a3)...(M an), with the composition
1676 // order being from left to right. Any (contiguous) segment where the
1677 // values ai, ai+1...aj are either all increasing or all decreasing,
1678 // can be implemented via a single vshuffvdd/vdealvdd respectively.
1680 // If there is a cycle (a1 a2 ... an) that does not involve M, it can
1681 // be written as (M an)(a1 a2 ... an)(M a1). The first two cycles can
1682 // then be folded to get (M a1 a2 ... an)(M a1), and the above procedure
1683 // can be used to generate a sequence of vshuffvdd/vdealvdd.
1686 // Assume M = 4 and consider a permutation (0 1)(2 3). It can be written
1687 // as (4 0 1)(4 0) composed with (4 2 3)(4 2), or simply
1688 // (4 0 1)(4 0)(4 2 3)(4 2).
1689 // It can then be expanded into swaps as
1690 // (4 0)(4 1)(4 0)(4 2)(4 3)(4 2),
1691 // and broken up into "increasing" segments as
1692 // [(4 0)(4 1)] [(4 0)(4 2)(4 3)] [(4 2)].
1693 // This is equivalent to
1694 // (4 0 1)(4 0 2 3)(4 2),
1695 // which can be implemented as 3 vshufvdd instructions.
1697 using CycleType = SmallVector<unsigned,8>;
1698 std::set<CycleType> Cycles;
1699 std::set<unsigned> All;
1701 for (unsigned I : Perm)
1704 // If the cycle contains LogLen-1, move it to the front of the cycle.
1705 // Otherwise, return the cycle unchanged.
1706 auto canonicalize = [LogLen](const CycleType &C) -> CycleType {
1707 unsigned LogPos, N = C.size();
1708 for (LogPos = 0; LogPos != N; ++LogPos)
1709 if (C[LogPos] == LogLen-1)
1714 CycleType NewC(C.begin()+LogPos, C.end());
1715 NewC.append(C.begin(), C.begin()+LogPos);
1719 auto pfs = [](const std::set<CycleType> &Cs, unsigned Len) {
1720 // Ordering: shuff: 5 0 1 2 3 4, deal: 5 4 3 2 1 0 (for Log=6),
1721 // for bytes zero is included, for halfwords is not.
1724 const CycleType &C = *Cs.begin();
1727 int D = Len - C.size();
1728 if (D != 0 && D != 1)
1731 bool IsDeal = true, IsShuff = true;
1732 for (unsigned I = 1; I != Len-D; ++I) {
1733 if (C[I] != Len-1-I)
1735 if (C[I] != I-(1-D)) // I-1, I
1738 // At most one, IsDeal or IsShuff, can be non-zero.
1739 assert(!(IsDeal || IsShuff) || IsDeal != IsShuff);
1740 static unsigned Deals[] = { Hexagon::V6_vdealb, Hexagon::V6_vdealh };
1741 static unsigned Shufs[] = { Hexagon::V6_vshuffb, Hexagon::V6_vshuffh };
1742 return IsDeal ? Deals[D] : (IsShuff ? Shufs[D] : 0);
1745 while (!All.empty()) {
1746 unsigned A = *All.begin();
1750 for (unsigned B = Perm[A]; B != A; B = Perm[B]) {
1756 Cycles.insert(canonicalize(C));
1759 MVT SingleTy = getSingleVT(MVT::i8);
1760 MVT PairTy = getPairVT(MVT::i8);
1762 // Recognize patterns for V6_vdeal{b,h} and V6_vshuff{b,h}.
1763 if (unsigned(VecLen) == HwLen) {
1764 if (unsigned SingleOpc = pfs(Cycles, LogLen)) {
1765 Results.push(SingleOpc, SingleTy, {Va});
1766 return OpRef::res(Results.top());
1770 SmallVector<unsigned,8> SwapElems;
1771 if (HwLen == unsigned(VecLen))
1772 SwapElems.push_back(LogLen-1);
1774 for (const CycleType &C : Cycles) {
1775 unsigned First = (C[0] == LogLen-1) ? 1 : 0;
1776 SwapElems.append(C.begin()+First, C.end());
1778 SwapElems.push_back(C[0]);
1781 const SDLoc &dl(Results.InpNode);
1782 OpRef Arg = !Extend ? Va
1783 : concat(Va, OpRef::undef(SingleTy), Results);
1785 for (unsigned I = 0, E = SwapElems.size(); I != E; ) {
1786 bool IsInc = I == E-1 || SwapElems[I] < SwapElems[I+1];
1787 unsigned S = (1u << SwapElems[I]);
1789 while (++I < E-1 && IsInc == (SwapElems[I] < SwapElems[I+1]))
1790 S |= 1u << SwapElems[I];
1791 // The above loop will not add a bit for the final SwapElems[I+1],
1793 S |= 1u << SwapElems[I];
1798 Results.push(Hexagon::A2_tfrsi, MVT::i32,
1799 { DAG.getTargetConstant(S, dl, MVT::i32) });
1800 Res.Opc = IsInc ? Hexagon::V6_vshuffvdd : Hexagon::V6_vdealvdd;
1802 Res.Ops = { OpRef::hi(Arg), OpRef::lo(Arg), OpRef::res(-1) };
1804 Arg = OpRef::res(Results.top());
1807 return !Extend ? Arg : OpRef::lo(Arg);
1810 OpRef HvxSelector::butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1811 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1812 // Butterfly shuffles.
1818 // The assumption here is that all elements picked by Mask are in the
1819 // first operand to the vector_shuffle. This assumption is enforced
1822 MVT ResTy = getSingleVT(MVT::i8);
1823 PermNetwork::Controls FC, RC;
1824 const SDLoc &dl(Results.InpNode);
1825 int VecLen = SM.Mask.size();
1827 for (int M : SM.Mask) {
1828 if (M != -1 && M >= VecLen)
1829 return OpRef::fail();
1832 // Try the deltas/benes for both single vectors and vector pairs.
1833 ForwardDeltaNetwork FN(SM.Mask);
1835 SDValue Ctl = getVectorConstant(FC, dl);
1836 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(Ctl)});
1837 return OpRef::res(Results.top());
1840 // Try reverse delta.
1841 ReverseDeltaNetwork RN(SM.Mask);
1843 SDValue Ctl = getVectorConstant(RC, dl);
1844 Results.push(Hexagon::V6_vrdelta, ResTy, {Va, OpRef(Ctl)});
1845 return OpRef::res(Results.top());
1849 BenesNetwork BN(SM.Mask);
1850 if (BN.run(FC, RC)) {
1851 SDValue CtlF = getVectorConstant(FC, dl);
1852 SDValue CtlR = getVectorConstant(RC, dl);
1853 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(CtlF)});
1854 Results.push(Hexagon::V6_vrdelta, ResTy,
1855 {OpRef::res(-1), OpRef(CtlR)});
1856 return OpRef::res(Results.top());
1859 return OpRef::fail();
1862 SDValue HvxSelector::getVectorConstant(ArrayRef<uint8_t> Data,
1864 SmallVector<SDValue, 128> Elems;
1865 for (uint8_t C : Data)
1866 Elems.push_back(DAG.getConstant(C, dl, MVT::i8));
1867 MVT VecTy = MVT::getVectorVT(MVT::i8, Data.size());
1868 SDValue BV = DAG.getBuildVector(VecTy, dl, Elems);
1869 SDValue LV = Lower.LowerOperation(BV, DAG);
1870 DAG.RemoveDeadNode(BV.getNode());
1874 void HvxSelector::selectShuffle(SDNode *N) {
1875 DEBUG_WITH_TYPE("isel", {
1876 dbgs() << "Starting " << __func__ << " on node:\n";
1879 MVT ResTy = N->getValueType(0).getSimpleVT();
1880 // Assume that vector shuffles operate on vectors of bytes.
1881 assert(ResTy.isVector() && ResTy.getVectorElementType() == MVT::i8);
1883 auto *SN = cast<ShuffleVectorSDNode>(N);
1884 std::vector<int> Mask(SN->getMask().begin(), SN->getMask().end());
1885 // This shouldn't really be necessary. Is it?
1886 for (int &Idx : Mask)
1887 if (Idx != -1 && Idx < 0)
1890 unsigned VecLen = Mask.size();
1891 bool HavePairs = (2*HwLen == VecLen);
1892 assert(ResTy.getSizeInBits() / 8 == VecLen);
1894 // Vd = vector_shuffle Va, Vb, Mask
1897 bool UseLeft = false, UseRight = false;
1898 for (unsigned I = 0; I != VecLen; ++I) {
1901 unsigned Idx = Mask[I];
1902 assert(Idx < 2*VecLen);
1909 DEBUG_WITH_TYPE("isel", {
1910 dbgs() << "VecLen=" << VecLen << " HwLen=" << HwLen << " UseLeft="
1911 << UseLeft << " UseRight=" << UseRight << " HavePairs="
1912 << HavePairs << '\n';
1914 // If the mask is all -1's, generate "undef".
1915 if (!UseLeft && !UseRight) {
1916 ISel.ReplaceNode(N, ISel.selectUndef(SDLoc(SN), ResTy).getNode());
1917 DAG.RemoveDeadNode(N);
1921 SDValue Vec0 = N->getOperand(0);
1922 SDValue Vec1 = N->getOperand(1);
1923 ResultStack Results(SN);
1924 Results.push(TargetOpcode::COPY, ResTy, {Vec0});
1925 Results.push(TargetOpcode::COPY, ResTy, {Vec1});
1926 OpRef Va = OpRef::res(Results.top()-1);
1927 OpRef Vb = OpRef::res(Results.top());
1929 OpRef Res = !HavePairs ? shuffs2(ShuffleMask(Mask), Va, Vb, Results)
1930 : shuffp2(ShuffleMask(Mask), Va, Vb, Results);
1932 bool Done = Res.isValid();
1934 // Make sure that Res is on the stack before materializing.
1935 Results.push(TargetOpcode::COPY, ResTy, {Res});
1936 materialize(Results);
1938 Done = scalarizeShuffle(Mask, SDLoc(N), ResTy, Vec0, Vec1, N);
1943 dbgs() << "Unhandled shuffle:\n";
1946 llvm_unreachable("Failed to select vector shuffle");
1950 void HvxSelector::selectRor(SDNode *N) {
1951 // If this is a rotation by less than 8, use V6_valignbi.
1952 MVT Ty = N->getValueType(0).getSimpleVT();
1954 SDValue VecV = N->getOperand(0);
1955 SDValue RotV = N->getOperand(1);
1956 SDNode *NewN = nullptr;
1958 if (auto *CN = dyn_cast<ConstantSDNode>(RotV.getNode())) {
1959 unsigned S = CN->getZExtValue();
1960 if (S % HST.getVectorLength() == 0) {
1961 NewN = VecV.getNode();
1962 } else if (isUInt<3>(S)) {
1963 SDValue C = DAG.getTargetConstant(S, dl, MVT::i32);
1964 NewN = DAG.getMachineNode(Hexagon::V6_valignbi, dl, Ty,
1970 NewN = DAG.getMachineNode(Hexagon::V6_vror, dl, Ty, {VecV, RotV});
1972 ISel.ReplaceNode(N, NewN);
1973 DAG.RemoveDeadNode(N);
1976 void HexagonDAGToDAGISel::SelectHvxShuffle(SDNode *N) {
1977 HvxSelector(*this, *CurDAG).selectShuffle(N);
1980 void HexagonDAGToDAGISel::SelectHvxRor(SDNode *N) {
1981 HvxSelector(*this, *CurDAG).selectRor(N);
1984 void HexagonDAGToDAGISel::SelectV65GatherPred(SDNode *N) {
1986 SDValue Chain = N->getOperand(0);
1987 SDValue Address = N->getOperand(2);
1988 SDValue Predicate = N->getOperand(3);
1989 SDValue Base = N->getOperand(4);
1990 SDValue Modifier = N->getOperand(5);
1991 SDValue Offset = N->getOperand(6);
1994 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
1997 llvm_unreachable("Unexpected HVX gather intrinsic.");
1998 case Intrinsic::hexagon_V6_vgathermhq:
1999 case Intrinsic::hexagon_V6_vgathermhq_128B:
2000 Opcode = Hexagon::V6_vgathermhq_pseudo;
2002 case Intrinsic::hexagon_V6_vgathermwq:
2003 case Intrinsic::hexagon_V6_vgathermwq_128B:
2004 Opcode = Hexagon::V6_vgathermwq_pseudo;
2006 case Intrinsic::hexagon_V6_vgathermhwq:
2007 case Intrinsic::hexagon_V6_vgathermhwq_128B:
2008 Opcode = Hexagon::V6_vgathermhwq_pseudo;
2012 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2013 SDValue Ops[] = { Address, Predicate, Base, Modifier, Offset, Chain };
2014 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2016 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2017 MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2018 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2020 ReplaceUses(N, Result);
2021 CurDAG->RemoveDeadNode(N);
2024 void HexagonDAGToDAGISel::SelectV65Gather(SDNode *N) {
2026 SDValue Chain = N->getOperand(0);
2027 SDValue Address = N->getOperand(2);
2028 SDValue Base = N->getOperand(3);
2029 SDValue Modifier = N->getOperand(4);
2030 SDValue Offset = N->getOperand(5);
2033 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2036 llvm_unreachable("Unexpected HVX gather intrinsic.");
2037 case Intrinsic::hexagon_V6_vgathermh:
2038 case Intrinsic::hexagon_V6_vgathermh_128B:
2039 Opcode = Hexagon::V6_vgathermh_pseudo;
2041 case Intrinsic::hexagon_V6_vgathermw:
2042 case Intrinsic::hexagon_V6_vgathermw_128B:
2043 Opcode = Hexagon::V6_vgathermw_pseudo;
2045 case Intrinsic::hexagon_V6_vgathermhw:
2046 case Intrinsic::hexagon_V6_vgathermhw_128B:
2047 Opcode = Hexagon::V6_vgathermhw_pseudo;
2051 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2052 SDValue Ops[] = { Address, Base, Modifier, Offset, Chain };
2053 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2055 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2056 MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2057 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2059 ReplaceUses(N, Result);
2060 CurDAG->RemoveDeadNode(N);
2063 void HexagonDAGToDAGISel::SelectHVXDualOutput(SDNode *N) {
2064 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2067 case Intrinsic::hexagon_V6_vaddcarry: {
2068 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2070 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2071 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2074 case Intrinsic::hexagon_V6_vaddcarry_128B: {
2075 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2077 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2078 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2081 case Intrinsic::hexagon_V6_vsubcarry: {
2082 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2084 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2085 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2088 case Intrinsic::hexagon_V6_vsubcarry_128B: {
2089 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2091 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2092 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2096 llvm_unreachable("Unexpected HVX dual output intrinsic.");
2098 ReplaceUses(N, Result);
2099 ReplaceUses(SDValue(N, 0), SDValue(Result, 0));
2100 ReplaceUses(SDValue(N, 1), SDValue(Result, 1));
2101 CurDAG->RemoveDeadNode(N);