LLVM 24.0.0git
LoongArchISelLowering.cpp
Go to the documentation of this file.
1//=- LoongArchISelLowering.cpp - LoongArch DAG Lowering Implementation ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that LoongArch uses to lower LLVM code into
10// a selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
15#include "LoongArch.h"
19#include "LoongArchSubtarget.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/IntrinsicsLoongArch.h"
34#include "llvm/Support/Debug.h"
39
40using namespace llvm;
41
42#define DEBUG_TYPE "loongarch-isel-lowering"
43
44STATISTIC(NumTailCalls, "Number of tail calls");
45
54
56 "loongarch-materialize-float-imm", cl::Hidden,
57 cl::desc("Maximum number of instructions used (including code sequence "
58 "to generate the value and moving the value to FPR) when "
59 "materializing floating-point immediates (default = 3)"),
61 cl::values(clEnumValN(NoMaterializeFPImm, "0", "Use constant pool"),
63 "Materialize FP immediate within 2 instructions"),
65 "Materialize FP immediate within 3 instructions"),
67 "Materialize FP immediate within 4 instructions"),
69 "Materialize FP immediate within 5 instructions"),
71 "Materialize FP immediate within 6 instructions "
72 "(behaves same as 5 on loongarch64)")));
73
74static cl::opt<bool> ZeroDivCheck("loongarch-check-zero-division", cl::Hidden,
75 cl::desc("Trap on integer division by zero."),
76 cl::init(false));
77
79 const LoongArchSubtarget &STI)
80 : TargetLowering(TM, STI), Subtarget(STI) {
81
82 MVT GRLenVT = Subtarget.getGRLenVT();
83
84 // Set up the register classes.
85
86 addRegisterClass(GRLenVT, &LoongArch::GPRRegClass);
87 if (Subtarget.hasBasicF())
88 addRegisterClass(MVT::f32, &LoongArch::FPR32RegClass);
89 if (Subtarget.hasBasicD())
90 addRegisterClass(MVT::f64, &LoongArch::FPR64RegClass);
91
92 static const MVT::SimpleValueType LSXVTs[] = {
93 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64};
94 static const MVT::SimpleValueType LASXVTs[] = {
95 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64, MVT::v8f32, MVT::v4f64};
96
97 if (Subtarget.hasExtLSX())
98 for (MVT VT : LSXVTs)
99 addRegisterClass(VT, &LoongArch::LSX128RegClass);
100
101 if (Subtarget.hasExtLASX())
102 for (MVT VT : LASXVTs)
103 addRegisterClass(VT, &LoongArch::LASX256RegClass);
104
105 // Set operations for LA32 and LA64.
106
108 MVT::i1, Promote);
109
114 if (Subtarget.hasBasicF())
118
121 GRLenVT, Custom);
122
124
129
131 setOperationAction(ISD::TRAP, MVT::Other, Legal);
132
136
138
139 // BITREV/REVB requires the 32S feature.
140 if (STI.has32S()) {
141 // Expand bitreverse.i16 with native-width bitrev and shift for now, before
142 // we get to know which of sll and revb.2h is faster.
145
146 // LA32 does not have REVB.2W and REVB.D due to the 64-bit operands, and
147 // the narrower REVB.W does not exist. But LA32 does have REVB.2H, so i16
148 // and i32 could still be byte-swapped relatively cheaply.
150 } else {
158 }
159
166
169
170 // Set operations for LA64 only.
171
172 if (Subtarget.is64Bit()) {
190
194 Custom);
196 }
197
198 // Set operations for LA32 only.
199
200 if (!Subtarget.is64Bit()) {
206 if (Subtarget.hasBasicD())
208 }
209
211
212 static const ISD::CondCode FPCCToExpand[] = {
215
216 // Set operations for 'F' feature.
217
218 if (Subtarget.hasBasicF()) {
219 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
220 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
222 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
223 setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
224
243 Subtarget.isSoftFPABI() ? LibCall : Custom);
245 Subtarget.isSoftFPABI() ? LibCall : Custom);
248 Subtarget.isSoftFPABI() ? LibCall : Custom);
251
252 if (Subtarget.is64Bit())
254
255 if (!Subtarget.hasBasicD()) {
257 if (Subtarget.is64Bit()) {
260 }
261 }
262 }
263
264 // Set operations for 'D' feature.
265
266 if (Subtarget.hasBasicD()) {
267 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
268 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
269 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
270 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
271 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
272 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
273 setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
274
294 Subtarget.isSoftFPABI() ? LibCall : Custom);
297 Subtarget.isSoftFPABI() ? LibCall : Custom);
298
299 if (Subtarget.is64Bit())
301 }
302
303 // Set operations for 'LSX' feature.
304
305 if (Subtarget.hasExtLSX()) {
307 // Expand all truncating stores and extending loads.
308 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
309 setTruncStoreAction(VT, InnerVT, Expand);
312 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
313 }
314 // By default everything must be expanded. Then we will selectively turn
315 // on ones that can be effectively codegen'd.
316 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
318 }
319
320 for (MVT VT : LSXVTs) {
324
328
333 }
334 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
337 Legal);
339 VT, Legal);
346 Expand);
361 }
362 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
364 for (MVT VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64})
366 for (MVT VT : {MVT::v4i32, MVT::v2i64}) {
370 }
372 for (MVT VT : {MVT::v4f32, MVT::v2f64}) {
380 VT, Expand);
388 }
390 setOperationAction(ISD::FCEIL, {MVT::f32, MVT::f64}, Legal);
391 setOperationAction(ISD::FFLOOR, {MVT::f32, MVT::f64}, Legal);
392 setOperationAction(ISD::FTRUNC, {MVT::f32, MVT::f64}, Legal);
393 setOperationAction(ISD::FROUNDEVEN, {MVT::f32, MVT::f64}, Legal);
394
395 for (MVT VT :
396 {MVT::v16i8, MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v8i16, MVT::v4i16,
397 MVT::v2i16, MVT::v4i32, MVT::v2i32, MVT::v2i64}) {
407 }
410 // We want to legalize this to an f64 load rather than an i64 load.
411 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
412 for (MVT VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16})
414 for (MVT VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64, MVT::v16i32, MVT::v8i64,
415 MVT::v16i64})
417 }
418
419 // Set operations for 'LASX' feature.
420
421 if (Subtarget.hasExtLASX()) {
422 for (MVT VT : LASXVTs) {
426
432
436 }
437 for (MVT VT : {MVT::v4i64, MVT::v8i32, MVT::v16i16, MVT::v32i8}) {
440 Legal);
442 VT, Legal);
449 Expand);
465 }
466 for (MVT VT : {MVT::v32i8, MVT::v16i16, MVT::v8i32})
468 for (MVT VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64})
470 for (MVT VT : {MVT::v8i32, MVT::v4i64})
472 for (MVT VT : {MVT::v8i32, MVT::v4i32, MVT::v4i64}) {
476 }
477 for (MVT VT : {MVT::v8f32, MVT::v4f64}) {
485 VT, Expand);
493 }
496 for (MVT VT : {MVT::v4i64, MVT::v8i32, MVT::v16i16}) {
500 }
501 for (MVT VT :
502 {MVT::v2i64, MVT::v4i32, MVT::v4i64, MVT::v8i16, MVT::v8i32}) {
505 }
506 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
508 }
509
510 // Set DAG combine for LA32 and LA64.
511 if (Subtarget.hasBasicF()) {
513 }
514
522
523 // On targets with the 32S feature, `select` is expanded into
524 // maskeqz + masknez + or (3 instructions), which is more expensive than
525 // on most other architectures where a single cmov-like instruction
526 // suffices. Enable a combine that can turn
527 // select cond, binop(X, Y), X -> binop X, (select cond, Y, 0)
528 // select cond, X, binop(X, Y) -> binop X, (select cond, 0, Y)
529 // for binop in {add, or, xor, sub}, replacing the 3-insn select (plus
530 // the original binop) with a single mask instruction plus the binop.
531 if (Subtarget.has32S())
533
534 // Set DAG combine for 'LSX' feature.
535
536 if (Subtarget.hasExtLSX()) {
549 }
550
551 // Set DAG combine for 'LASX' feature.
552 if (Subtarget.hasExtLASX()) {
555 }
556
557 // Compute derived properties from the register classes.
558 computeRegisterProperties(Subtarget.getRegisterInfo());
559
561
564
565 setMaxAtomicSizeInBitsSupported(Subtarget.getGRLen());
566
568
569 // Function alignments.
571 // Set preferred alignments.
572 setPrefFunctionAlignment(Subtarget.getPrefFunctionAlignment());
573 setPrefLoopAlignment(Subtarget.getPrefLoopAlignment());
574 setMaxBytesForAlignment(Subtarget.getMaxBytesForAlignment());
575
576 // cmpxchg sizes down to 8 bits become legal if LAMCAS is available.
577 if (Subtarget.hasLAMCAS())
579
580 if (Subtarget.hasSCQ()) {
583 }
584
585 // Disable strict node mutation.
586 IsStrictFPEnabled = true;
587}
588
590 const GlobalAddressSDNode *GA) const {
591 // In order to maximise the opportunity for common subexpression elimination,
592 // keep a separate ADD node for the global address offset instead of folding
593 // it in the global address node. Later peephole optimisations may choose to
594 // fold it back in when profitable.
595 return false;
596}
597
599 SelectionDAG &DAG) const {
600 switch (Op.getOpcode()) {
602 return lowerATOMIC_FENCE(Op, DAG);
604 return lowerEH_DWARF_CFA(Op, DAG);
606 return lowerGlobalAddress(Op, DAG);
608 return lowerGlobalTLSAddress(Op, DAG);
610 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
612 return lowerINTRINSIC_W_CHAIN(Op, DAG);
614 return lowerINTRINSIC_VOID(Op, DAG);
616 return lowerBlockAddress(Op, DAG);
617 case ISD::JumpTable:
618 return lowerJumpTable(Op, DAG);
619 case ISD::SHL_PARTS:
620 return lowerShiftLeftParts(Op, DAG);
621 case ISD::SRA_PARTS:
622 return lowerShiftRightParts(Op, DAG, true);
623 case ISD::SRL_PARTS:
624 return lowerShiftRightParts(Op, DAG, false);
626 return lowerConstantPool(Op, DAG);
627 case ISD::FP_TO_SINT:
628 return lowerFP_TO_SINT(Op, DAG);
629 case ISD::FP_TO_UINT:
630 return lowerFP_TO_UINT(Op, DAG);
632 return lowerFP_TO_SINT_SAT(Op, DAG);
633 case ISD::BITCAST:
634 return lowerBITCAST(Op, DAG);
635 case ISD::UINT_TO_FP:
636 return lowerUINT_TO_FP(Op, DAG);
637 case ISD::SINT_TO_FP:
638 return lowerSINT_TO_FP(Op, DAG);
639 case ISD::VASTART:
640 return lowerVASTART(Op, DAG);
641 case ISD::FRAMEADDR:
642 return lowerFRAMEADDR(Op, DAG);
643 case ISD::RETURNADDR:
644 return lowerRETURNADDR(Op, DAG);
646 return lowerSET_ROUNDING(Op, DAG);
648 return lowerGET_ROUNDING(Op, DAG);
650 return lowerWRITE_REGISTER(Op, DAG);
652 return lowerINSERT_VECTOR_ELT(Op, DAG);
654 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
656 return lowerBUILD_VECTOR(Op, DAG);
658 return lowerCONCAT_VECTORS(Op, DAG);
660 return lowerVECTOR_SHUFFLE(Op, DAG);
661 case ISD::BITREVERSE:
662 return lowerBITREVERSE(Op, DAG);
664 return lowerSCALAR_TO_VECTOR(Op, DAG);
665 case ISD::PREFETCH:
666 return lowerPREFETCH(Op, DAG);
667 case ISD::SELECT:
668 return lowerSELECT(Op, DAG);
669 case ISD::BRCOND:
670 return lowerBRCOND(Op, DAG);
671 case ISD::FP_TO_FP16:
672 return lowerFP_TO_FP16(Op, DAG);
673 case ISD::FP16_TO_FP:
674 return lowerFP16_TO_FP(Op, DAG);
675 case ISD::FP_TO_BF16:
676 return lowerFP_TO_BF16(Op, DAG);
677 case ISD::BF16_TO_FP:
678 return lowerBF16_TO_FP(Op, DAG);
680 return lowerVECREDUCE_ADD(Op, DAG);
681 case ISD::ROTL:
682 case ISD::ROTR:
683 return lowerRotate(Op, DAG);
691 return lowerVECREDUCE(Op, DAG);
692 case ISD::ConstantFP:
693 return lowerConstantFP(Op, DAG);
694 case ISD::SETCC:
695 return lowerSETCC(Op, DAG);
696 case ISD::FP_ROUND:
697 return lowerFP_ROUND(Op, DAG);
698 case ISD::FP_EXTEND:
699 return lowerFP_EXTEND(Op, DAG);
701 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
703 return lowerDYNAMIC_STACKALLOC(Op, DAG);
704 case ISD::ANY_EXTEND:
705 return lowerANY_EXTEND(Op, DAG);
706 case ISD::VSELECT:
707 return lowerVSELECT(Op, DAG);
708 }
709 return SDValue();
710}
711
712// Helper to attempt to return a cheaper, bit-inverted version of \p V.
714 // TODO: don't always ignore oneuse constraints.
716 EVT VT = V.getValueType();
717
718 // Match not(xor X, -1) -> X.
719 if (V.getOpcode() == ISD::XOR &&
720 (ISD::isBuildVectorAllOnes(V.getOperand(1)) ||
721 isAllOnesConstant(V.getOperand(1))))
722 return V.getOperand(0);
723
724 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
725 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
726 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
727 if (SDValue Not = isNOT(V.getOperand(0), DAG)) {
728 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
729 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
730 V.getOperand(1));
731 }
732 }
733
734 // Match not(SplatVector(not(X)) -> SplatVector(X).
735 if (V.getOpcode() == ISD::BUILD_VECTOR) {
736 if (SDValue SplatValue =
737 cast<BuildVectorSDNode>(V.getNode())->getSplatValue()) {
738 if (!V->isOnlyUserOf(SplatValue.getNode()))
739 return SDValue();
740
741 if (SDValue Not = isNOT(SplatValue, DAG)) {
742 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
743 return DAG.getSplat(VT, SDLoc(Not), Not);
744 }
745 }
746 }
747
748 // Match not(or(not(X),not(Y))) -> and(X, Y).
749 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
750 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
751 // TODO: Handle cases with single NOT operand -> VANDN
752 if (SDValue Op1 = isNOT(V.getOperand(1), DAG))
753 if (SDValue Op0 = isNOT(V.getOperand(0), DAG))
754 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
755 DAG.getBitcast(VT, Op1));
756 }
757
758 // TODO: Add more matching patterns. Such as,
759 // not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
760 // not(slt(C, X)) -> slt(X - 1, C)
761 return SDValue();
762}
763
764// Combine two ISD::FP_ROUND / LoongArchISD::VFCVT nodes with same type to
765// LoongArchISD::VFCVT. For example:
766// x1 = fp_round x, 0
767// y1 = fp_round y, 0
768// z = concat_vectors x1, y1
769// Or
770// x1 = LoongArch::VFCVT undef, x
771// y1 = LoongArch::VFCVT undef, y
772// z = LoongArchISD::VPACKEV y1, x1; or LoongArchISD::VPERMI y1, x1, 68
773// can be combined to:
774// z = LoongArch::VFCVT y, x
777 assert(((N->getOpcode() == ISD::CONCAT_VECTORS && N->getNumOperands() == 2) ||
778 (N->getOpcode() == LoongArchISD::VPACKEV) ||
779 (N->getOpcode() == LoongArchISD::VPERMI)) &&
780 "Invalid Node");
781
782 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
783 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
784 unsigned Opcode0 = Op0.getOpcode();
785 unsigned Opcode1 = Op1.getOpcode();
786 if (Opcode0 != Opcode1)
787 return SDValue();
788
789 if (Opcode0 != ISD::FP_ROUND && Opcode0 != LoongArchISD::VFCVT)
790 return SDValue();
791
792 // Check if two nodes have only one use.
793 if (!Op0.hasOneUse() || !Op1.hasOneUse())
794 return SDValue();
795
796 EVT VT = N.getValueType();
797 EVT SVT0 = Op0.getValueType();
798 EVT SVT1 = Op1.getValueType();
799 // Check if two nodes have the same result type.
800 if (SVT0 != SVT1)
801 return SDValue();
802
803 // Check if two nodes have the same operand type.
804 EVT SSVT0 = Op0.getOperand(0).getValueType();
805 EVT SSVT1 = Op1.getOperand(0).getValueType();
806 if (SSVT0 != SSVT1)
807 return SDValue();
808
809 if (N->getOpcode() == ISD::CONCAT_VECTORS && Opcode0 == ISD::FP_ROUND) {
810 if (Subtarget.hasExtLASX() && VT.is256BitVector() && SVT0 == MVT::v4f32 &&
811 SSVT0 == MVT::v4f64) {
812 // A vector_shuffle is required in the final step, as xvfcvt instruction
813 // operates on each 128-bit segament as a lane.
814 SDValue Res = DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v8f32,
815 Op1.getOperand(0), Op0.getOperand(0));
816 SDValue Undef = DAG.getUNDEF(Res.getValueType());
817 // After VFCVT, the high part of Res comes from the high parts of Op0 and
818 // Op1, and the low part comes from the low parts of Op0 and Op1. However,
819 // the desired order requires Op0 to fully occupy the lower half and Op1
820 // the upper half of Res. The Mask reorders the elements of Res to achieve
821 // this:
822 // - The first four elements (0, 1, 4, 5) come from Op0.
823 // - The next four elements (2, 3, 6, 7) come from Op1.
824 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
825 Res = DAG.getVectorShuffle(Res.getValueType(), DL, Res, Undef, Mask);
826 return DAG.getBitcast(VT, Res);
827 }
828 }
829
830 if ((N->getOpcode() == LoongArchISD::VPACKEV ||
831 N->getOpcode() == LoongArchISD::VPERMI) &&
832 Opcode0 == LoongArchISD::VFCVT) {
833 // For VPACKEV or VPERMI, check if the first operation of VFCVT is undef.
834 if (!Op0.getOperand(0).isUndef() || !Op1.getOperand(0).isUndef())
835 return SDValue();
836
837 if (!Subtarget.hasExtLSX() || SVT0 != MVT::v4f32 || SSVT0 != MVT::v2f64)
838 return SDValue();
839
840 if (N->getOpcode() == LoongArchISD::VPACKEV &&
841 (VT == MVT::v2i64 || VT == MVT::v2f64)) {
842 SDValue Res = DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32,
843 Op0.getOperand(1), Op1.getOperand(1));
844 return DAG.getBitcast(VT, Res);
845 }
846
847 if (N->getOpcode() == LoongArchISD::VPERMI && VT == MVT::v4f32) {
848 int64_t Imm = cast<ConstantSDNode>(N->getOperand(2))->getSExtValue();
849 if (Imm != 68)
850 return SDValue();
851 return DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32, Op0.getOperand(1),
852 Op1.getOperand(1));
853 }
854 }
855
856 return SDValue();
857}
858
859SDValue LoongArchTargetLowering::lowerFP_ROUND(SDValue Op,
860 SelectionDAG &DAG) const {
861 SDLoc DL(Op);
862 SDValue In = Op.getOperand(0);
863 MVT VT = Op.getSimpleValueType();
864 MVT SVT = In.getSimpleValueType();
865
866 if (VT == MVT::v4f32 && SVT == MVT::v4f64) {
867 SDValue Lo, Hi;
868 std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
869 return DAG.getNode(LoongArchISD::VFCVT, DL, VT, Hi, Lo);
870 }
871
872 return SDValue();
873}
874
875SDValue LoongArchTargetLowering::lowerFP_EXTEND(SDValue Op,
876 SelectionDAG &DAG) const {
877
878 SDLoc DL(Op);
879 EVT VT = Op.getValueType();
880 SDValue Src = Op->getOperand(0);
881 EVT SVT = Src.getValueType();
882
883 bool V2F32ToV2F64 =
884 VT == MVT::v2f64 && SVT == MVT::v2f32 && Subtarget.hasExtLSX();
885 bool V4F32ToV4F64 =
886 VT == MVT::v4f64 && SVT == MVT::v4f32 && Subtarget.hasExtLASX();
887 if (!V2F32ToV2F64 && !V4F32ToV4F64)
888 return SDValue();
889
890 // Check if Op is the high part of vector.
891 auto CheckVecHighPart = [](SDValue Op) {
893 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
894 SDValue SOp = Op.getOperand(0);
895 EVT SVT = SOp.getValueType();
896 if (!SVT.isVector() || (SVT.getVectorNumElements() % 2 != 0))
897 return SDValue();
898
899 const uint64_t Imm = Op.getConstantOperandVal(1);
900 if (Imm == SVT.getVectorNumElements() / 2)
901 return SOp;
902 return SDValue();
903 }
904 return SDValue();
905 };
906
907 unsigned Opcode;
908 SDValue VFCVTOp;
909 EVT WideOpVT = SVT.getSimpleVT().getDoubleNumVectorElementsVT();
910 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
911
912 // If the operand of ISD::FP_EXTEND comes from the high part of vector,
913 // generate LoongArchISD::VFCVTH, otherwise LoongArchISD::VFCVTL.
914 if (SDValue V = CheckVecHighPart(Src)) {
915 assert(V.getValueSizeInBits() == WideOpVT.getSizeInBits() &&
916 "Unexpected wide vector");
917 Opcode = LoongArchISD::VFCVTH;
918 VFCVTOp = DAG.getBitcast(WideOpVT, V);
919 } else {
920 Opcode = LoongArchISD::VFCVTL;
921 VFCVTOp = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideOpVT,
922 DAG.getUNDEF(WideOpVT), Src, ZeroIdx);
923 }
924
925 // v2f64 = fp_extend v2f32
926 if (V2F32ToV2F64)
927 return DAG.getNode(Opcode, DL, VT, VFCVTOp);
928
929 // v4f64 = fp_extend v4f32
930 if (V4F32ToV4F64) {
931 // XVFCVT instruction operates on each 128-bit segment as a lane, so a
932 // vector_shuffle is required firstly.
933 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
934 SDValue Res = DAG.getVectorShuffle(WideOpVT, DL, VFCVTOp,
935 DAG.getUNDEF(WideOpVT), Mask);
936 Res = DAG.getNode(Opcode, DL, VT, Res);
937 return Res;
938 }
939
940 return SDValue();
941}
942
943SDValue LoongArchTargetLowering::lowerVSELECT(SDValue Op,
944 SelectionDAG &DAG) const {
945 SDValue Cond = Op.getOperand(0);
946 SDValue LHS = Op.getOperand(1);
947 SDValue RHS = Op.getOperand(2);
948 MVT VT = Op.getSimpleValueType();
949 SDLoc DL(Op);
950
951 // Try to lower vselect to vector_shuffle. All cases with constant
952 // build_vector condition will be handled. NOTE: On 32-bit platform, vselect
953 // with v2i64/v4i64 type condition will never enter this because of the extra
954 // bitcast. It can be considered separately later.
956 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Cond.getNode());
957 APInt SplatValue, SplatUndef;
958 unsigned SplatBitSize;
959 bool HasAnyUndefs;
960
961 // If the Cond is a BUILD_VECTOR with splat constants, using a vldi or
962 // constant broadcast instruction and a vbitsel is better.
963 if (BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
964 /*MinSplatBits=*/8) &&
965 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
966 SplatBitSize == 64))
967 return Op;
968
970 EVT CondVT = Cond.getValueType();
971 int NumElts = CondVT.getVectorNumElements();
972 Mask.resize(NumElts, -1);
973 for (int i = 0; i < NumElts; ++i) {
974 SDValue CondOp = Cond.getOperand(i);
975 if (CondOp.isUndef())
976 continue;
977 auto *CondElt = dyn_cast<ConstantSDNode>(CondOp);
978 if (CondElt->getZExtValue() == 0)
979 Mask[i] = i + NumElts;
980 else
981 Mask[i] = i;
982 }
983
984 return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
985 }
986
987 // Fallback to match patterns in tablegen.
988 return Op;
989}
990
991SDValue LoongArchTargetLowering::lowerConstantFP(SDValue Op,
992 SelectionDAG &DAG) const {
993 EVT VT = Op.getValueType();
994 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
995 const APFloat &FPVal = CFP->getValueAPF();
996 SDLoc DL(CFP);
997
998 assert((VT == MVT::f32 && Subtarget.hasBasicF()) ||
999 (VT == MVT::f64 && Subtarget.hasBasicD()));
1000
1001 // If value is 0.0 or -0.0, just ignore it.
1002 if (FPVal.isZero())
1003 return SDValue();
1004
1005 // If lsx enabled, use cheaper 'vldi' instruction if possible.
1006 if (isFPImmVLDILegal(FPVal, VT))
1007 return SDValue();
1008
1009 // The legalizer builds immediates the size of a GPR from their bits. Fall
1010 // back to a load from the constant pool for expensive immediates.
1011 if (VT.getSizeInBits() == Subtarget.getGRLen() ||
1012 !isFPImmCheapInGPR(FPVal, VT))
1013 return SDValue();
1014
1015 // Construct as integer, and move to float register.
1016 APInt INTVal = FPVal.bitcastToAPInt();
1017 if (VT == MVT::f32) {
1018 assert(Subtarget.is64Bit());
1019 SDValue NewVal = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
1020 DAG.getConstant(INTVal, DL, MVT::i32));
1021 return DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, VT, NewVal);
1022 }
1023
1024 assert(VT == MVT::f64 && !Subtarget.is64Bit());
1025 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
1026 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
1027 return DAG.getNode(LoongArchISD::MOVGR2FR_D_LO_HI, DL, VT, Lo, Hi);
1028}
1029
1030// Ensure SETCC result and operand have the same bit width; isel does not
1031// support mismatched widths.
1032SDValue LoongArchTargetLowering::lowerSETCC(SDValue Op,
1033 SelectionDAG &DAG) const {
1034 SDLoc DL(Op);
1035 EVT ResultVT = Op.getValueType();
1036 EVT OperandVT = Op.getOperand(0).getValueType();
1037
1038 EVT SetCCResultVT =
1039 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT);
1040
1041 if (ResultVT == SetCCResultVT)
1042 return Op;
1043
1044 assert(Op.getOperand(0).getValueType() == Op.getOperand(1).getValueType() &&
1045 "SETCC operands must have the same type!");
1046
1047 SDValue SetCCNode =
1048 DAG.getNode(ISD::SETCC, DL, SetCCResultVT, Op.getOperand(0),
1049 Op.getOperand(1), Op.getOperand(2));
1050
1051 if (ResultVT.bitsGT(SetCCResultVT))
1052 SetCCNode = DAG.getNode(ISD::SIGN_EXTEND, DL, ResultVT, SetCCNode);
1053 else if (ResultVT.bitsLT(SetCCResultVT))
1054 SetCCNode = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, SetCCNode);
1055
1056 return SetCCNode;
1057}
1058
1059// Lower SIGN_EXTEND_VECTOR_INREG with VSLLWIL, which sign-extends the low half
1060// of the source elements (and shifts them left by 0).
1061// For example:
1062// %b = sext <8 x i8> %a to <8 x i16>
1063// can be lowered to:
1064// VSLLWIL.H.B vr1, vr1, 0
1065//
1066// VSLLWIL is slower than VILVL and VSRAI, so a 4x extension instead
1067// replicates each source element across its destination element by
1068// interleaving the source with itself twice, then shifts the copy in the top
1069// bits down arithmetically:
1070// %b = sext <4 x i8> %a to <4 x i32>
1071// can be lowered to:
1072// VILVL.B vr1, vr1, vr1
1073// VILVL.H vr1, vr1, vr1
1074// VSRAI.W vr1, vr1, 24
1075//
1076// If every extended source element is already all-ones or all-zeros, e.g. a
1077// comparison result, the interleaves alone produce the sign extension, so
1078// neither VSLLWIL nor the VSRAI is needed:
1079// %b = sext <8 x i8> %mask to <8 x i16>
1080// can be lowered to:
1081// VILVL.B vr1, vr1, vr1
1082SDValue LoongArchTargetLowering::lowerSIGN_EXTEND_VECTOR_INREG(
1083 SDValue Op, SelectionDAG &DAG) const {
1084 SDLoc DL(Op);
1085 SDValue Src = Op.getOperand(0);
1086
1087 // Only whole 128-bit vectors of simple element types can be lowered this
1088 // way; fall back to the default lowering for other sources.
1089 if (!Src.getValueType().isSimple())
1090 return SDValue();
1091 MVT SrcVT = Src.getSimpleValueType();
1092 MVT DstVT = Op.getSimpleValueType();
1093 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
1094 unsigned DstEltBits = DstVT.getScalarSizeInBits();
1095
1096 // Leave larger ratios to the generic shuffle + shift expansion, which only
1097 // needs a single VEXTRINS to move the second element into place.
1098 unsigned Ratio = DstEltBits / SrcEltBits;
1099 if (!SrcVT.is128BitVector() || Ratio > 4)
1100 return SDValue();
1101
1102 // Only the low elements of the source are extended.
1103 APInt DemandedElts = APInt::getLowBitsSet(SrcVT.getVectorNumElements(),
1104 DstVT.getVectorNumElements());
1105 bool IsSignSplat = DAG.ComputeNumSignBits(Src, DemandedElts) == SrcEltBits;
1106
1107 if (Ratio == 2 && !IsSignSplat)
1108 return DAG.getNode(LoongArchISD::VSLLWIL, DL, DstVT, Src,
1109 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
1110
1111 SDValue Res = Src;
1112 for (unsigned EltBits = SrcEltBits; EltBits < DstEltBits; EltBits *= 2) {
1113 MVT VT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), 128 / EltBits);
1114 Res = DAG.getBitcast(VT, Res);
1115 Res = DAG.getNode(LoongArchISD::VILVL, DL, VT, Res, Res);
1116 }
1117 Res = DAG.getBitcast(DstVT, Res);
1118 if (IsSignSplat)
1119 return Res;
1120 return DAG.getNode(ISD::SRA, DL, DstVT, Res,
1121 DAG.getConstant(DstEltBits - SrcEltBits, DL, DstVT));
1122}
1123
1124// ANY_EXTEND can be replaced by ZERO_EXTEND when LASX is enabled.
1125SDValue LoongArchTargetLowering::lowerANY_EXTEND(SDValue Op,
1126 SelectionDAG &DAG) const {
1127 assert(Subtarget.hasExtLASX());
1128 // We don't have corresponding instrunction for ANY_EXTEND, lowering it to
1129 // ZERO_EXTEND won't break its semantics, while avoid scalar extract/insert.
1130 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(Op), Op.getValueType(),
1131 Op.getOperand(0));
1132}
1133
1134// Lower vecreduce_add using vhaddw instructions.
1135// For Example:
1136// call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %a)
1137// can be lowered to:
1138// VHADDW_D_W vr0, vr0, vr0
1139// VHADDW_Q_D vr0, vr0, vr0
1140// VPICKVE2GR_D a0, vr0, 0
1141// ADDI_W a0, a0, 0
1142SDValue LoongArchTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
1143 SelectionDAG &DAG) const {
1144
1145 SDLoc DL(Op);
1146 MVT OpVT = Op.getSimpleValueType();
1147 SDValue Val = Op.getOperand(0);
1148
1149 unsigned NumEles = Val.getSimpleValueType().getVectorNumElements();
1150 unsigned EleBits = Val.getSimpleValueType().getScalarSizeInBits();
1151 unsigned ResBits = OpVT.getScalarSizeInBits();
1152
1153 unsigned LegalVecSize = 128;
1154 bool isLASX256Vector =
1155 Subtarget.hasExtLASX() && Val.getValueSizeInBits() == 256;
1156
1157 // Ensure operand type legal or enable it legal.
1158 while (!isTypeLegal(Val.getSimpleValueType())) {
1159 Val = DAG.WidenVector(Val, DL);
1160 }
1161
1162 // NumEles is designed for iterations count, v4i32 for LSX
1163 // and v8i32 for LASX should have the same count.
1164 if (isLASX256Vector) {
1165 NumEles /= 2;
1166 LegalVecSize = 256;
1167 }
1168
1169 EleBits *= 2;
1170 for (unsigned i = 1; i < NumEles; i *= 2, EleBits *= 2) {
1171 EleBits = std::min(EleBits, 64u);
1172 MVT IntTy = MVT::getIntegerVT(EleBits);
1173 MVT VecTy = MVT::getVectorVT(IntTy, LegalVecSize / EleBits);
1174 Val = DAG.getNode(LoongArchISD::VHADDW, DL, VecTy, Val, Val);
1175 }
1176
1177 if (isLASX256Vector) {
1178 SDValue Tmp = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, Val,
1179 DAG.getConstant(2, DL, Subtarget.getGRLenVT()));
1180 Val = DAG.getNode(ISD::ADD, DL, MVT::v4i64, Tmp, Val);
1181 }
1182
1183 Val = DAG.getBitcast(MVT::getVectorVT(OpVT, LegalVecSize / ResBits), Val);
1184 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT, Val,
1185 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
1186}
1187
1188// Lower vecreduce_and/or/xor/[s/u]max/[s/u]min.
1189// For Example:
1190// call i32 @llvm.vector.reduce.smax.v4i32(<4 x i32> %a)
1191// can be lowered to:
1192// VBSRL_V vr1, vr0, 8
1193// VMAX_W vr0, vr1, vr0
1194// VBSRL_V vr1, vr0, 4
1195// VMAX_W vr0, vr1, vr0
1196// VPICKVE2GR_W a0, vr0, 0
1197// For 256 bit vector, it is illegal and will be spilt into
1198// two 128 bit vector by default then processed by this.
1199SDValue LoongArchTargetLowering::lowerVECREDUCE(SDValue Op,
1200 SelectionDAG &DAG) const {
1201 SDLoc DL(Op);
1202
1203 MVT OpVT = Op.getSimpleValueType();
1204 SDValue Val = Op.getOperand(0);
1205
1206 unsigned NumEles = Val.getSimpleValueType().getVectorNumElements();
1207 unsigned EleBits = Val.getSimpleValueType().getScalarSizeInBits();
1208
1209 // Ensure operand type legal or enable it legal.
1210 while (!isTypeLegal(Val.getSimpleValueType())) {
1211 Val = DAG.WidenVector(Val, DL);
1212 }
1213
1214 unsigned Opcode = ISD::getVecReduceBaseOpcode(Op.getOpcode());
1215 MVT VecTy = Val.getSimpleValueType();
1216 MVT GRLenVT = Subtarget.getGRLenVT();
1217
1218 for (int i = NumEles; i > 1; i /= 2) {
1219 SDValue ShiftAmt = DAG.getConstant(i * EleBits / 16, DL, GRLenVT);
1220 SDValue Tmp = DAG.getNode(LoongArchISD::VBSRL, DL, VecTy, Val, ShiftAmt);
1221 Val = DAG.getNode(Opcode, DL, VecTy, Tmp, Val);
1222 }
1223
1224 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT, Val,
1225 DAG.getConstant(0, DL, GRLenVT));
1226}
1227
1228SDValue LoongArchTargetLowering::lowerPREFETCH(SDValue Op,
1229 SelectionDAG &DAG) const {
1230 unsigned IsData = Op.getConstantOperandVal(4);
1231
1232 // We don't support non-data prefetch.
1233 // Just preserve the chain.
1234 if (!IsData)
1235 return Op.getOperand(0);
1236
1237 return Op;
1238}
1239
1240SDValue LoongArchTargetLowering::lowerRotate(SDValue Op,
1241 SelectionDAG &DAG) const {
1242 MVT VT = Op.getSimpleValueType();
1243 assert(VT.isVector() && "Unexpected type");
1244
1245 SDLoc DL(Op);
1246 SDValue R = Op.getOperand(0);
1247 SDValue Amt = Op.getOperand(1);
1248 unsigned Opcode = Op.getOpcode();
1249 unsigned EltSizeInBits = VT.getScalarSizeInBits();
1250
1251 auto checkCstSplat = [](SDValue V, APInt &CstSplatValue) {
1252 if (V.getOpcode() != ISD::BUILD_VECTOR)
1253 return false;
1254 if (SDValue SplatValue =
1255 cast<BuildVectorSDNode>(V.getNode())->getSplatValue()) {
1256 if (auto *C = dyn_cast<ConstantSDNode>(SplatValue)) {
1257 CstSplatValue = C->getAPIntValue();
1258 return true;
1259 }
1260 }
1261 return false;
1262 };
1263
1264 // Check for constant splat rotation amount.
1265 APInt CstSplatValue;
1266 bool IsCstSplat = checkCstSplat(Amt, CstSplatValue);
1267 bool isROTL = Opcode == ISD::ROTL;
1268
1269 // Check for splat rotate by zero.
1270 if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
1271 return R;
1272
1273 // LoongArch targets always prefer ISD::ROTR.
1274 if (isROTL) {
1275 SDValue Zero = DAG.getConstant(0, DL, VT);
1276 return DAG.getNode(ISD::ROTR, DL, VT, R,
1277 DAG.getNode(ISD::SUB, DL, VT, Zero, Amt));
1278 }
1279
1280 // Rotate by a immediate.
1281 if (IsCstSplat) {
1282 // ISD::ROTR: Attemp to rotate by a positive immediate.
1283 SDValue Bits = DAG.getConstant(EltSizeInBits, DL, VT);
1284 if (SDValue Urem =
1285 DAG.FoldConstantArithmetic(ISD::UREM, DL, VT, {Amt, Bits}))
1286 return DAG.getNode(Opcode, DL, VT, R, Urem);
1287 }
1288
1289 return Op;
1290}
1291
1292// Return true if Val is equal to (setcc LHS, RHS, CC).
1293// Return false if Val is the inverse of (setcc LHS, RHS, CC).
1294// Otherwise, return std::nullopt.
1295static std::optional<bool> matchSetCC(SDValue LHS, SDValue RHS,
1296 ISD::CondCode CC, SDValue Val) {
1297 assert(Val->getOpcode() == ISD::SETCC);
1298 SDValue LHS2 = Val.getOperand(0);
1299 SDValue RHS2 = Val.getOperand(1);
1300 ISD::CondCode CC2 = Val.getOperandCondCode(2);
1301
1302 if (LHS == LHS2 && RHS == RHS2) {
1303 if (CC == CC2)
1304 return true;
1305 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
1306 return false;
1307 } else if (LHS == RHS2 && RHS == LHS2) {
1309 if (CC == CC2)
1310 return true;
1311 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
1312 return false;
1313 }
1314
1315 return std::nullopt;
1316}
1317
1320 SDValue CondV = N->getOperand(0);
1321 SDValue TrueV = N->getOperand(1);
1322 SDValue FalseV = N->getOperand(2);
1323 MVT VT = N->getSimpleValueType(0);
1324 SDLoc DL(N);
1325
1326 // (select c, -1, y) -> -c | y
1327 if (isAllOnesConstant(TrueV)) {
1328 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1329 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(FalseV));
1330 }
1331 // (select c, y, -1) -> (c-1) | y
1332 if (isAllOnesConstant(FalseV)) {
1333 SDValue Neg =
1334 DAG.getNode(ISD::ADD, DL, VT, CondV, DAG.getAllOnesConstant(DL, VT));
1335 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(TrueV));
1336 }
1337
1338 // (select c, 0, y) -> (c-1) & y
1339 if (isNullConstant(TrueV)) {
1340 SDValue Neg =
1341 DAG.getNode(ISD::ADD, DL, VT, CondV, DAG.getAllOnesConstant(DL, VT));
1342 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(FalseV));
1343 }
1344 // (select c, y, 0) -> -c & y
1345 if (isNullConstant(FalseV)) {
1346 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1347 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(TrueV));
1348 }
1349
1350 // select c, ~x, x --> xor -c, x
1351 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV)) {
1352 const APInt &TrueVal = TrueV->getAsAPIntVal();
1353 const APInt &FalseVal = FalseV->getAsAPIntVal();
1354 if (~TrueVal == FalseVal) {
1355 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1356 return DAG.getNode(ISD::XOR, DL, VT, Neg, FalseV);
1357 }
1358 }
1359
1360 // Try to fold (select (setcc lhs, rhs, cc), truev, falsev) into bitwise ops
1361 // when both truev and falsev are also setcc.
1362 if (CondV.getOpcode() == ISD::SETCC && TrueV.getOpcode() == ISD::SETCC &&
1363 FalseV.getOpcode() == ISD::SETCC) {
1364 SDValue LHS = CondV.getOperand(0);
1365 SDValue RHS = CondV.getOperand(1);
1367
1368 // (select x, x, y) -> x | y
1369 // (select !x, x, y) -> x & y
1370 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, TrueV)) {
1371 return DAG.getNode(*MatchResult ? ISD::OR : ISD::AND, DL, VT, TrueV,
1372 DAG.getFreeze(FalseV));
1373 }
1374 // (select x, y, x) -> x & y
1375 // (select !x, y, x) -> x | y
1376 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, FalseV)) {
1377 return DAG.getNode(*MatchResult ? ISD::AND : ISD::OR, DL, VT,
1378 DAG.getFreeze(TrueV), FalseV);
1379 }
1380 }
1381
1382 return SDValue();
1383}
1384
1385// Transform `binOp (select cond, x, c0), c1` where `c0` and `c1` are constants
1386// into `select cond, binOp(x, c1), binOp(c0, c1)` if profitable.
1387// For now we only consider transformation profitable if `binOp(c0, c1)` ends up
1388// being `0` or `-1`. In such cases we can replace `select` with `and`.
1389// TODO: Should we also do this if `binOp(c0, c1)` is cheaper to materialize
1390// than `c0`?
1391static SDValue
1394 unsigned SelOpNo = 0;
1395 SDValue Sel = BO->getOperand(0);
1396 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
1397 SelOpNo = 1;
1398 Sel = BO->getOperand(1);
1399 }
1400
1401 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1402 return SDValue();
1403
1404 unsigned ConstSelOpNo = 1;
1405 unsigned OtherSelOpNo = 2;
1406 if (!isa<ConstantSDNode>(Sel->getOperand(ConstSelOpNo))) {
1407 ConstSelOpNo = 2;
1408 OtherSelOpNo = 1;
1409 }
1410 SDValue ConstSelOp = Sel->getOperand(ConstSelOpNo);
1411 ConstantSDNode *ConstSelOpNode = dyn_cast<ConstantSDNode>(ConstSelOp);
1412 if (!ConstSelOpNode || ConstSelOpNode->isOpaque())
1413 return SDValue();
1414
1415 SDValue ConstBinOp = BO->getOperand(SelOpNo ^ 1);
1416 ConstantSDNode *ConstBinOpNode = dyn_cast<ConstantSDNode>(ConstBinOp);
1417 if (!ConstBinOpNode || ConstBinOpNode->isOpaque())
1418 return SDValue();
1419
1420 SDLoc DL(Sel);
1421 EVT VT = BO->getValueType(0);
1422
1423 SDValue NewConstOps[2] = {ConstSelOp, ConstBinOp};
1424 if (SelOpNo == 1)
1425 std::swap(NewConstOps[0], NewConstOps[1]);
1426
1427 SDValue NewConstOp =
1428 DAG.FoldConstantArithmetic(BO->getOpcode(), DL, VT, NewConstOps);
1429 if (!NewConstOp)
1430 return SDValue();
1431
1432 const APInt &NewConstAPInt = NewConstOp->getAsAPIntVal();
1433 if (!NewConstAPInt.isZero() && !NewConstAPInt.isAllOnes())
1434 return SDValue();
1435
1436 SDValue OtherSelOp = Sel->getOperand(OtherSelOpNo);
1437 SDValue NewNonConstOps[2] = {OtherSelOp, ConstBinOp};
1438 if (SelOpNo == 1)
1439 std::swap(NewNonConstOps[0], NewNonConstOps[1]);
1440 SDValue NewNonConstOp = DAG.getNode(BO->getOpcode(), DL, VT, NewNonConstOps);
1441
1442 SDValue NewT = (ConstSelOpNo == 1) ? NewConstOp : NewNonConstOp;
1443 SDValue NewF = (ConstSelOpNo == 1) ? NewNonConstOp : NewConstOp;
1444 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewT, NewF);
1445}
1446
1447// Changes the condition code and swaps operands if necessary, so the SetCC
1448// operation matches one of the comparisons supported directly by branches
1449// in the LoongArch ISA. May adjust compares to favor compare with 0 over
1450// compare with 1/-1.
1452 ISD::CondCode &CC, SelectionDAG &DAG) {
1453 // If this is a single bit test that can't be handled by ANDI, shift the
1454 // bit to be tested to the MSB and perform a signed compare with 0.
1455 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
1456 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
1457 isa<ConstantSDNode>(LHS.getOperand(1))) {
1458 uint64_t Mask = LHS.getConstantOperandVal(1);
1459 if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) {
1460 unsigned ShAmt = 0;
1461 if (isPowerOf2_64(Mask)) {
1463 ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
1464 } else {
1465 ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask);
1466 }
1467
1468 LHS = LHS.getOperand(0);
1469 if (ShAmt != 0)
1470 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
1471 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
1472 return;
1473 }
1474 }
1475
1476 if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1477 int64_t C = RHSC->getSExtValue();
1478 switch (CC) {
1479 default:
1480 break;
1481 case ISD::SETGT:
1482 // Convert X > -1 to X >= 0.
1483 if (C == -1) {
1484 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1485 CC = ISD::SETGE;
1486 return;
1487 }
1488 break;
1489 case ISD::SETLT:
1490 // Convert X < 1 to 0 >= X.
1491 if (C == 1) {
1492 RHS = LHS;
1493 LHS = DAG.getConstant(0, DL, RHS.getValueType());
1494 CC = ISD::SETGE;
1495 return;
1496 }
1497 break;
1498 }
1499 }
1500
1501 switch (CC) {
1502 default:
1503 break;
1504 case ISD::SETGT:
1505 case ISD::SETLE:
1506 case ISD::SETUGT:
1507 case ISD::SETULE:
1509 std::swap(LHS, RHS);
1510 break;
1511 }
1512}
1513
1514SDValue LoongArchTargetLowering::lowerSELECT(SDValue Op,
1515 SelectionDAG &DAG) const {
1516 SDValue CondV = Op.getOperand(0);
1517 SDValue TrueV = Op.getOperand(1);
1518 SDValue FalseV = Op.getOperand(2);
1519 SDLoc DL(Op);
1520 MVT VT = Op.getSimpleValueType();
1521 MVT GRLenVT = Subtarget.getGRLenVT();
1522
1523 if (SDValue V = combineSelectToBinOp(Op.getNode(), DAG, Subtarget))
1524 return V;
1525
1526 if (Op.hasOneUse()) {
1527 unsigned UseOpc = Op->user_begin()->getOpcode();
1528 if (isBinOp(UseOpc) && DAG.isSafeToSpeculativelyExecute(UseOpc)) {
1529 SDNode *BinOp = *Op->user_begin();
1530 if (SDValue NewSel = foldBinOpIntoSelectIfProfitable(*Op->user_begin(),
1531 DAG, Subtarget)) {
1532 DAG.ReplaceAllUsesWith(BinOp, &NewSel);
1533 // Opcode check is necessary because foldBinOpIntoSelectIfProfitable
1534 // may return a constant node and cause crash in lowerSELECT.
1535 if (NewSel.getOpcode() == ISD::SELECT)
1536 return lowerSELECT(NewSel, DAG);
1537 return NewSel;
1538 }
1539 }
1540 }
1541
1542 // If the condition is not an integer SETCC which operates on GRLenVT, we need
1543 // to emit a LoongArchISD::SELECT_CC comparing the condition to zero. i.e.:
1544 // (select condv, truev, falsev)
1545 // -> (loongarchisd::select_cc condv, zero, setne, truev, falsev)
1546 if (CondV.getOpcode() != ISD::SETCC ||
1547 CondV.getOperand(0).getSimpleValueType() != GRLenVT) {
1548 SDValue Zero = DAG.getConstant(0, DL, GRLenVT);
1549 SDValue SetNE = DAG.getCondCode(ISD::SETNE);
1550
1551 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
1552
1553 return DAG.getNode(LoongArchISD::SELECT_CC, DL, VT, Ops);
1554 }
1555
1556 // If the CondV is the output of a SETCC node which operates on GRLenVT
1557 // inputs, then merge the SETCC node into the lowered LoongArchISD::SELECT_CC
1558 // to take advantage of the integer compare+branch instructions. i.e.: (select
1559 // (setcc lhs, rhs, cc), truev, falsev)
1560 // -> (loongarchisd::select_cc lhs, rhs, cc, truev, falsev)
1561 SDValue LHS = CondV.getOperand(0);
1562 SDValue RHS = CondV.getOperand(1);
1563 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
1564
1565 // Special case for a select of 2 constants that have a difference of 1.
1566 // Normally this is done by DAGCombine, but if the select is introduced by
1567 // type legalization or op legalization, we miss it. Restricting to SETLT
1568 // case for now because that is what signed saturating add/sub need.
1569 // FIXME: We don't need the condition to be SETLT or even a SETCC,
1570 // but we would probably want to swap the true/false values if the condition
1571 // is SETGE/SETLE to avoid an XORI.
1572 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
1573 CCVal == ISD::SETLT) {
1574 const APInt &TrueVal = TrueV->getAsAPIntVal();
1575 const APInt &FalseVal = FalseV->getAsAPIntVal();
1576 if (TrueVal - 1 == FalseVal)
1577 return DAG.getNode(ISD::ADD, DL, VT, CondV, FalseV);
1578 if (TrueVal + 1 == FalseVal)
1579 return DAG.getNode(ISD::SUB, DL, VT, FalseV, CondV);
1580 }
1581
1582 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
1583 // 1 < x ? x : 1 -> 0 < x ? x : 1
1584 if (isOneConstant(LHS) && (CCVal == ISD::SETLT || CCVal == ISD::SETULT) &&
1585 RHS == TrueV && LHS == FalseV) {
1586 LHS = DAG.getConstant(0, DL, VT);
1587 // 0 <u x is the same as x != 0.
1588 if (CCVal == ISD::SETULT) {
1589 std::swap(LHS, RHS);
1590 CCVal = ISD::SETNE;
1591 }
1592 }
1593
1594 // x <s -1 ? x : -1 -> x <s 0 ? x : -1
1595 if (isAllOnesConstant(RHS) && CCVal == ISD::SETLT && LHS == TrueV &&
1596 RHS == FalseV) {
1597 RHS = DAG.getConstant(0, DL, VT);
1598 }
1599
1600 SDValue TargetCC = DAG.getCondCode(CCVal);
1601
1602 if (isa<ConstantSDNode>(TrueV) && !isa<ConstantSDNode>(FalseV)) {
1603 // (select (setcc lhs, rhs, CC), constant, falsev)
1604 // -> (select (setcc lhs, rhs, InverseCC), falsev, constant)
1605 std::swap(TrueV, FalseV);
1606 TargetCC = DAG.getCondCode(ISD::getSetCCInverse(CCVal, LHS.getValueType()));
1607 }
1608
1609 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
1610 return DAG.getNode(LoongArchISD::SELECT_CC, DL, VT, Ops);
1611}
1612
1613SDValue LoongArchTargetLowering::lowerBRCOND(SDValue Op,
1614 SelectionDAG &DAG) const {
1615 SDValue CondV = Op.getOperand(1);
1616 SDLoc DL(Op);
1617 MVT GRLenVT = Subtarget.getGRLenVT();
1618
1619 if (CondV.getOpcode() == ISD::SETCC) {
1620 if (CondV.getOperand(0).getValueType() == GRLenVT) {
1621 SDValue LHS = CondV.getOperand(0);
1622 SDValue RHS = CondV.getOperand(1);
1623 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
1624
1625 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
1626
1627 SDValue TargetCC = DAG.getCondCode(CCVal);
1628 return DAG.getNode(LoongArchISD::BR_CC, DL, Op.getValueType(),
1629 Op.getOperand(0), LHS, RHS, TargetCC,
1630 Op.getOperand(2));
1631 } else if (CondV.getOperand(0).getValueType().isFloatingPoint()) {
1632 return DAG.getNode(LoongArchISD::BRCOND, DL, Op.getValueType(),
1633 Op.getOperand(0), CondV, Op.getOperand(2));
1634 }
1635 }
1636
1637 return DAG.getNode(LoongArchISD::BR_CC, DL, Op.getValueType(),
1638 Op.getOperand(0), CondV, DAG.getConstant(0, DL, GRLenVT),
1639 DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
1640}
1641
1642SDValue
1643LoongArchTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
1644 SelectionDAG &DAG) const {
1645 SDLoc DL(Op);
1646 MVT OpVT = Op.getSimpleValueType();
1647
1648 SDValue Vector = DAG.getUNDEF(OpVT);
1649 SDValue Val = Op.getOperand(0);
1650 SDValue Idx = DAG.getConstant(0, DL, Subtarget.getGRLenVT());
1651
1652 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, OpVT, Vector, Val, Idx);
1653}
1654
1655SDValue LoongArchTargetLowering::lowerBITREVERSE(SDValue Op,
1656 SelectionDAG &DAG) const {
1657 EVT ResTy = Op->getValueType(0);
1658 SDValue Src = Op->getOperand(0);
1659 SDLoc DL(Op);
1660
1661 // LoongArchISD::BITREV_8B is not supported on LA32.
1662 if (!Subtarget.is64Bit() && (ResTy == MVT::v16i8 || ResTy == MVT::v32i8))
1663 return SDValue();
1664
1665 EVT NewVT = ResTy.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
1666 unsigned int OrigEltNum = ResTy.getVectorNumElements();
1667 unsigned int NewEltNum = NewVT.getVectorNumElements();
1668
1669 SDValue NewSrc = DAG.getNode(ISD::BITCAST, DL, NewVT, Src);
1670
1672 for (unsigned int i = 0; i < NewEltNum; i++) {
1673 SDValue Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, NewSrc,
1674 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
1675 unsigned RevOp = (ResTy == MVT::v16i8 || ResTy == MVT::v32i8)
1676 ? (unsigned)LoongArchISD::BITREV_8B
1677 : (unsigned)ISD::BITREVERSE;
1678 Ops.push_back(DAG.getNode(RevOp, DL, MVT::i64, Op));
1679 }
1680 SDValue Res =
1681 DAG.getNode(ISD::BITCAST, DL, ResTy, DAG.getBuildVector(NewVT, DL, Ops));
1682
1683 switch (ResTy.getSimpleVT().SimpleTy) {
1684 default:
1685 return SDValue();
1686 case MVT::v16i8:
1687 case MVT::v32i8:
1688 return Res;
1689 case MVT::v8i16:
1690 case MVT::v16i16:
1691 case MVT::v4i32:
1692 case MVT::v8i32: {
1694 for (unsigned int i = 0; i < NewEltNum; i++)
1695 for (int j = OrigEltNum / NewEltNum - 1; j >= 0; j--)
1696 Mask.push_back(j + (OrigEltNum / NewEltNum) * i);
1697 return DAG.getVectorShuffle(ResTy, DL, Res, DAG.getUNDEF(ResTy), Mask);
1698 }
1699 }
1700}
1701
1702// Widen element type to get a new mask value (if possible).
1703// For example:
1704// shufflevector <4 x i32> %a, <4 x i32> %b,
1705// <4 x i32> <i32 6, i32 7, i32 2, i32 3>
1706// is equivalent to:
1707// shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
1708// can be lowered to:
1709// VPACKOD_D vr0, vr0, vr1
1711 SDValue V1, SDValue V2, SelectionDAG &DAG) {
1712 unsigned EltBits = VT.getScalarSizeInBits();
1713
1714 if (EltBits > 32 || EltBits == 1)
1715 return SDValue();
1716
1717 SmallVector<int, 8> NewMask;
1718 if (widenShuffleMaskElts(Mask, NewMask)) {
1719 MVT NewEltVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(EltBits * 2)
1720 : MVT::getIntegerVT(EltBits * 2);
1721 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
1722 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
1723 SDValue NewV1 = DAG.getBitcast(NewVT, V1);
1724 SDValue NewV2 = DAG.getBitcast(NewVT, V2);
1725 return DAG.getBitcast(
1726 VT, DAG.getVectorShuffle(NewVT, DL, NewV1, NewV2, NewMask));
1727 }
1728 }
1729
1730 return SDValue();
1731}
1732
1733/// Attempts to match a shuffle mask against the VBSLL, VBSRL, VSLLI and VSRLI
1734/// instruction.
1735// The funciton matches elements from one of the input vector shuffled to the
1736// left or right with zeroable elements 'shifted in'. It handles both the
1737// strictly bit-wise element shifts and the byte shfit across an entire 128-bit
1738// lane.
1739// Mostly copied from X86.
1740static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
1741 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
1742 int MaskOffset, const APInt &Zeroable) {
1743 int Size = Mask.size();
1744 unsigned SizeInBits = Size * ScalarSizeInBits;
1745
1746 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
1747 for (int i = 0; i < Size; i += Scale)
1748 for (int j = 0; j < Shift; ++j)
1749 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
1750 return false;
1751
1752 return true;
1753 };
1754
1755 auto isSequentialOrUndefInRange = [&](unsigned Pos, unsigned Size, int Low,
1756 int Step = 1) {
1757 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
1758 if (!(Mask[i] == -1 || Mask[i] == Low))
1759 return false;
1760 return true;
1761 };
1762
1763 auto MatchShift = [&](int Shift, int Scale, bool Left) {
1764 for (int i = 0; i != Size; i += Scale) {
1765 unsigned Pos = Left ? i + Shift : i;
1766 unsigned Low = Left ? i : i + Shift;
1767 unsigned Len = Scale - Shift;
1768 if (!isSequentialOrUndefInRange(Pos, Len, Low + MaskOffset))
1769 return -1;
1770 }
1771
1772 int ShiftEltBits = ScalarSizeInBits * Scale;
1773 bool ByteShift = ShiftEltBits > 64;
1774 Opcode = Left ? (ByteShift ? LoongArchISD::VBSLL : LoongArchISD::VSLLI)
1775 : (ByteShift ? LoongArchISD::VBSRL : LoongArchISD::VSRLI);
1776 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
1777
1778 // Normalize the scale for byte shifts to still produce an i64 element
1779 // type.
1780 Scale = ByteShift ? Scale / 2 : Scale;
1781
1782 // We need to round trip through the appropriate type for the shift.
1783 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
1784 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
1785 : MVT::getVectorVT(ShiftSVT, Size / Scale);
1786 return (int)ShiftAmt;
1787 };
1788
1789 unsigned MaxWidth = 128;
1790 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
1791 for (int Shift = 1; Shift != Scale; ++Shift)
1792 for (bool Left : {true, false})
1793 if (CheckZeros(Shift, Scale, Left)) {
1794 int ShiftAmt = MatchShift(Shift, Scale, Left);
1795 if (0 < ShiftAmt)
1796 return ShiftAmt;
1797 }
1798
1799 // no match
1800 return -1;
1801}
1802
1803/// Lower VECTOR_SHUFFLE as shift (if possible).
1804///
1805/// For example:
1806/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
1807/// <4 x i32> <i32 4, i32 0, i32 1, i32 2>
1808/// is lowered to:
1809/// (VBSLL_V $v0, $v0, 4)
1810///
1811/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
1812/// <4 x i32> <i32 4, i32 0, i32 4, i32 2>
1813/// is lowered to:
1814/// (VSLLI_D $v0, $v0, 32)
1816 MVT VT, SDValue V1, SDValue V2,
1817 SelectionDAG &DAG,
1819 const APInt &Zeroable) {
1820 int Size = Mask.size();
1821 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
1822
1823 MVT ShiftVT;
1824 SDValue V = V1;
1825 unsigned Opcode;
1826
1827 // Try to match shuffle against V1 shift.
1828 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
1829 Mask, 0, Zeroable);
1830
1831 // If V1 failed, try to match shuffle against V2 shift.
1832 if (ShiftAmt < 0) {
1833 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
1834 Mask, Size, Zeroable);
1835 V = V2;
1836 }
1837
1838 if (ShiftAmt < 0)
1839 return SDValue();
1840
1841 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
1842 "Illegal integer vector type");
1843 V = DAG.getBitcast(ShiftVT, V);
1844 V = DAG.getNode(Opcode, DL, ShiftVT, V,
1845 DAG.getConstant(ShiftAmt, DL, Subtarget.getGRLenVT()));
1846 return DAG.getBitcast(VT, V);
1847}
1848
1849/// Determine whether a range fits a regular pattern of values.
1850/// This function accounts for the possibility of jumping over the End iterator.
1851template <typename ValType>
1852static bool
1854 unsigned CheckStride,
1856 ValType ExpectedIndex, unsigned ExpectedIndexStride) {
1857 auto &I = Begin;
1858
1859 while (I != End) {
1860 if (*I != -1 && *I != ExpectedIndex)
1861 return false;
1862 ExpectedIndex += ExpectedIndexStride;
1863
1864 // Incrementing past End is undefined behaviour so we must increment one
1865 // step at a time and check for End at each step.
1866 for (unsigned n = 0; n < CheckStride && I != End; ++n, ++I)
1867 ; // Empty loop body.
1868 }
1869 return true;
1870}
1871
1872/// Compute whether each element of a shuffle is zeroable.
1873///
1874/// A "zeroable" vector shuffle element is one which can be lowered to zero.
1876 SDValue V2, APInt &KnownUndef,
1877 APInt &KnownZero) {
1878 int Size = Mask.size();
1879 KnownUndef = KnownZero = APInt::getZero(Size);
1880
1882 V2 = peekThroughBitcasts(V2);
1883
1884 bool V1IsZero = ISD::isBuildVectorAllZeros(V1);
1885 bool V2IsZero = ISD::isBuildVectorAllZeros(V2);
1886
1887 int VectorSizeInBits = V1.getValueSizeInBits();
1888 int ScalarSizeInBits = VectorSizeInBits / Size;
1889 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
1890 (void)ScalarSizeInBits;
1891
1892 for (int i = 0; i < Size; ++i) {
1893 int M = Mask[i];
1894 if (M < 0) {
1895 KnownUndef.setBit(i);
1896 continue;
1897 }
1898 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
1899 KnownZero.setBit(i);
1900 continue;
1901 }
1902 }
1903}
1904
1905/// Test whether a shuffle mask is equivalent within each sub-lane.
1906///
1907/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
1908/// non-trivial to compute in the face of undef lanes. The representation is
1909/// suitable for use with existing 128-bit shuffles as entries from the second
1910/// vector have been remapped to [LaneSize, 2*LaneSize).
1911static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
1912 ArrayRef<int> Mask,
1913 SmallVectorImpl<int> &RepeatedMask) {
1914 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
1915 RepeatedMask.assign(LaneSize, -1);
1916 int Size = Mask.size();
1917 for (int i = 0; i < Size; ++i) {
1918 assert(Mask[i] == -1 || Mask[i] >= 0);
1919 if (Mask[i] < 0)
1920 continue;
1921 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
1922 // This entry crosses lanes, so there is no way to model this shuffle.
1923 return false;
1924
1925 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
1926 // Adjust second vector indices to start at LaneSize instead of Size.
1927 int LocalM =
1928 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
1929 if (RepeatedMask[i % LaneSize] < 0)
1930 // This is the first non-undef entry in this slot of a 128-bit lane.
1931 RepeatedMask[i % LaneSize] = LocalM;
1932 else if (RepeatedMask[i % LaneSize] != LocalM)
1933 // Found a mismatch with the repeated mask.
1934 return false;
1935 }
1936 return true;
1937}
1938
1939/// Attempts to match vector shuffle as byte rotation.
1941 ArrayRef<int> Mask) {
1942
1943 SDValue Lo, Hi;
1944 SmallVector<int, 16> RepeatedMask;
1945
1946 if (!isRepeatedShuffleMask(128, VT, Mask, RepeatedMask))
1947 return -1;
1948
1949 int NumElts = RepeatedMask.size();
1950 int Rotation = 0;
1951 int Scale = 16 / NumElts;
1952
1953 for (int i = 0; i < NumElts; ++i) {
1954 int M = RepeatedMask[i];
1955 assert((M == -1 || (0 <= M && M < (2 * NumElts))) &&
1956 "Unexpected mask index.");
1957 if (M < 0)
1958 continue;
1959
1960 // Determine where a rotated vector would have started.
1961 int StartIdx = i - (M % NumElts);
1962 if (StartIdx == 0)
1963 return -1;
1964
1965 // If we found the tail of a vector the rotation must be the missing
1966 // front. If we found the head of a vector, it must be how much of the
1967 // head.
1968 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
1969
1970 if (Rotation == 0)
1971 Rotation = CandidateRotation;
1972 else if (Rotation != CandidateRotation)
1973 return -1;
1974
1975 // Compute which value this mask is pointing at.
1976 SDValue MaskV = M < NumElts ? V1 : V2;
1977
1978 // Compute which of the two target values this index should be assigned
1979 // to. This reflects whether the high elements are remaining or the low
1980 // elements are remaining.
1981 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
1982
1983 // Either set up this value if we've not encountered it before, or check
1984 // that it remains consistent.
1985 if (!TargetV)
1986 TargetV = MaskV;
1987 else if (TargetV != MaskV)
1988 return -1;
1989 }
1990
1991 // Check that we successfully analyzed the mask, and normalize the results.
1992 assert(Rotation != 0 && "Failed to locate a viable rotation!");
1993 assert((Lo || Hi) && "Failed to find a rotated input vector!");
1994 if (!Lo)
1995 Lo = Hi;
1996 else if (!Hi)
1997 Hi = Lo;
1998
1999 V1 = Lo;
2000 V2 = Hi;
2001
2002 return Rotation * Scale;
2003}
2004
2005/// Lower VECTOR_SHUFFLE as byte rotate (if possible).
2006///
2007/// For example:
2008/// %shuffle = shufflevector <2 x i64> %a, <2 x i64> %b,
2009/// <2 x i32> <i32 3, i32 0>
2010/// is lowered to:
2011/// (VBSRL_V $v1, $v1, 8)
2012/// (VBSLL_V $v0, $v0, 8)
2013/// (VOR_V $v0, $V0, $v1)
2014static SDValue
2016 SDValue V1, SDValue V2, SelectionDAG &DAG,
2018
2019 SDValue Lo = V1, Hi = V2;
2020 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
2021 if (ByteRotation <= 0)
2022 return SDValue();
2023
2024 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
2025 Lo = DAG.getBitcast(ByteVT, Lo);
2026 Hi = DAG.getBitcast(ByteVT, Hi);
2027
2028 int LoByteShift = 16 - ByteRotation;
2029 int HiByteShift = ByteRotation;
2030 MVT GRLenVT = Subtarget.getGRLenVT();
2031
2032 SDValue LoShift = DAG.getNode(LoongArchISD::VBSLL, DL, ByteVT, Lo,
2033 DAG.getConstant(LoByteShift, DL, GRLenVT));
2034 SDValue HiShift = DAG.getNode(LoongArchISD::VBSRL, DL, ByteVT, Hi,
2035 DAG.getConstant(HiByteShift, DL, GRLenVT));
2036 return DAG.getBitcast(VT, DAG.getNode(ISD::OR, DL, ByteVT, LoShift, HiShift));
2037}
2038
2039/// Lower VECTOR_SHUFFLE as ZERO_EXTEND Or ANY_EXTEND (if possible).
2040///
2041/// For example:
2042/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
2043/// <4 x i32> <i32 0, i32 4, i32 1, i32 4>
2044/// %3 = bitcast <4 x i32> %2 to <2 x i64>
2045/// is lowered to:
2046/// (VREPLI $v1, 0)
2047/// (VILVL $v0, $v1, $v0)
2049 ArrayRef<int> Mask, MVT VT,
2050 SDValue V1, SDValue V2,
2051 SelectionDAG &DAG,
2052 const APInt &Zeroable) {
2053 int Bits = VT.getSizeInBits();
2054 int EltBits = VT.getScalarSizeInBits();
2055 int NumElements = VT.getVectorNumElements();
2056
2057 if (Zeroable.isAllOnes())
2058 return DAG.getConstant(0, DL, VT);
2059
2060 // Define a helper function to check a particular ext-scale and lower to it if
2061 // valid.
2062 auto Lower = [&](int Scale) -> SDValue {
2063 SDValue InputV;
2064 bool AnyExt = true;
2065 int Offset = 0;
2066 for (int i = 0; i < NumElements; i++) {
2067 int M = Mask[i];
2068 if (M < 0)
2069 continue;
2070 if (i % Scale != 0) {
2071 // Each of the extended elements need to be zeroable.
2072 if (!Zeroable[i])
2073 return SDValue();
2074
2075 AnyExt = false;
2076 continue;
2077 }
2078
2079 // Each of the base elements needs to be consecutive indices into the
2080 // same input vector.
2081 SDValue V = M < NumElements ? V1 : V2;
2082 M = M % NumElements;
2083 if (!InputV) {
2084 InputV = V;
2085 Offset = M - (i / Scale);
2086
2087 // These offset can't be handled
2088 if (Offset % (NumElements / Scale))
2089 return SDValue();
2090 } else if (InputV != V)
2091 return SDValue();
2092
2093 if (M != (Offset + (i / Scale)))
2094 return SDValue(); // Non-consecutive strided elements.
2095 }
2096
2097 // If we fail to find an input, we have a zero-shuffle which should always
2098 // have already been handled.
2099 if (!InputV)
2100 return SDValue();
2101
2102 do {
2103 unsigned VilVLoHi = LoongArchISD::VILVL;
2104 if (Offset >= (NumElements / 2)) {
2105 VilVLoHi = LoongArchISD::VILVH;
2106 Offset -= (NumElements / 2);
2107 }
2108
2109 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
2110 SDValue Ext =
2111 AnyExt ? DAG.getFreeze(InputV) : DAG.getConstant(0, DL, InputVT);
2112 InputV = DAG.getBitcast(InputVT, InputV);
2113 Ext = DAG.getBitcast(InputVT, Ext);
2114 InputV = DAG.getNode(VilVLoHi, DL, InputVT, Ext, InputV);
2115 Scale /= 2;
2116 EltBits *= 2;
2117 NumElements /= 2;
2118 } while (Scale > 1);
2119 return DAG.getBitcast(VT, InputV);
2120 };
2121
2122 // Each iteration, try extending the elements half as much, but into twice as
2123 // many elements.
2124 for (int NumExtElements = Bits / 64; NumExtElements < NumElements;
2125 NumExtElements *= 2) {
2126 if (SDValue V = Lower(NumElements / NumExtElements))
2127 return V;
2128 }
2129 return SDValue();
2130}
2131
2132/// Lower VECTOR_SHUFFLE into VREPLVEI (if possible).
2133///
2134/// VREPLVEI performs vector broadcast based on an element specified by an
2135/// integer immediate, with its mask being similar to:
2136/// <x, x, x, ...>
2137/// where x is any valid index.
2138///
2139/// When undef's appear in the mask they are treated as if they were whatever
2140/// value is necessary in order to fit the above form.
2141static SDValue
2143 SDValue V1, SelectionDAG &DAG,
2145 int SplatIndex = -1;
2146 for (const auto &M : Mask) {
2147 if (M != -1) {
2148 SplatIndex = M;
2149 break;
2150 }
2151 }
2152
2153 if (SplatIndex == -1)
2154 return DAG.getUNDEF(VT);
2155
2156 assert(SplatIndex < (int)Mask.size() && "Out of bounds mask index");
2157 if (fitsRegularPattern<int>(Mask.begin(), 1, Mask.end(), SplatIndex, 0)) {
2158 return DAG.getNode(LoongArchISD::VREPLVEI, DL, VT, V1,
2159 DAG.getConstant(SplatIndex, DL, Subtarget.getGRLenVT()));
2160 }
2161
2162 return SDValue();
2163}
2164
2165/// Lower VECTOR_SHUFFLE into VSHUF4I (if possible).
2166///
2167/// VSHUF4I splits the vector into blocks of four elements, then shuffles these
2168/// elements according to a <4 x i2> constant (encoded as an integer immediate).
2169///
2170/// It is therefore possible to lower into VSHUF4I when the mask takes the form:
2171/// <a, b, c, d, a+4, b+4, c+4, d+4, a+8, b+8, c+8, d+8, ...>
2172/// When undef's appear they are treated as if they were whatever value is
2173/// necessary in order to fit the above forms.
2174///
2175/// For example:
2176/// %2 = shufflevector <8 x i16> %0, <8 x i16> undef,
2177/// <8 x i32> <i32 3, i32 2, i32 1, i32 0,
2178/// i32 7, i32 6, i32 5, i32 4>
2179/// is lowered to:
2180/// (VSHUF4I_H $v0, $v1, 27)
2181/// where the 27 comes from:
2182/// 3 + (2 << 2) + (1 << 4) + (0 << 6)
2183static SDValue
2185 SDValue V1, SDValue V2, SelectionDAG &DAG,
2187
2188 unsigned SubVecSize = 4;
2189 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2190 SubVecSize = 2;
2191
2192 int SubMask[4] = {-1, -1, -1, -1};
2193 for (unsigned i = 0; i < SubVecSize; ++i) {
2194 for (unsigned j = i; j < Mask.size(); j += SubVecSize) {
2195 int M = Mask[j];
2196
2197 // Convert from vector index to 4-element subvector index
2198 // If an index refers to an element outside of the subvector then give up
2199 if (M != -1) {
2200 M -= 4 * (j / SubVecSize);
2201 if (M < 0 || M >= 4)
2202 return SDValue();
2203 }
2204
2205 // If the mask has an undef, replace it with the current index.
2206 // Note that it might still be undef if the current index is also undef
2207 if (SubMask[i] == -1)
2208 SubMask[i] = M;
2209 // Check that non-undef values are the same as in the mask. If they
2210 // aren't then give up
2211 else if (M != -1 && M != SubMask[i])
2212 return SDValue();
2213 }
2214 }
2215
2216 // Calculate the immediate. Replace any remaining undefs with zero
2217 int Imm = 0;
2218 for (int i = SubVecSize - 1; i >= 0; --i) {
2219 int M = SubMask[i];
2220
2221 if (M == -1)
2222 M = 0;
2223
2224 Imm <<= 2;
2225 Imm |= M & 0x3;
2226 }
2227
2228 MVT GRLenVT = Subtarget.getGRLenVT();
2229
2230 // Return vshuf4i.d
2231 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2232 return DAG.getNode(LoongArchISD::VSHUF4I_D, DL, VT, V1, V2,
2233 DAG.getConstant(Imm, DL, GRLenVT));
2234
2235 return DAG.getNode(LoongArchISD::VSHUF4I, DL, VT, V1,
2236 DAG.getConstant(Imm, DL, GRLenVT));
2237}
2238
2239/// Lower VECTOR_SHUFFLE whose result is the reversed source vector.
2240///
2241/// It is possible to do optimization for VECTOR_SHUFFLE performing vector
2242/// reverse whose mask likes:
2243/// <7, 6, 5, 4, 3, 2, 1, 0>
2244///
2245/// When undef's appear in the mask they are treated as if they were whatever
2246/// value is necessary in order to fit the above forms.
2247static SDValue
2249 SDValue V1, SelectionDAG &DAG,
2251 // Only vectors with i8/i16 elements which cannot match other patterns
2252 // directly needs to do this.
2253 if (VT != MVT::v16i8 && VT != MVT::v8i16 && VT != MVT::v32i8 &&
2254 VT != MVT::v16i16)
2255 return SDValue();
2256
2257 if (!ShuffleVectorInst::isReverseMask(Mask, Mask.size()))
2258 return SDValue();
2259
2260 int WidenNumElts = VT.getVectorNumElements() / 4;
2261 SmallVector<int, 16> WidenMask(WidenNumElts, -1);
2262 for (int i = 0; i < WidenNumElts; ++i)
2263 WidenMask[i] = WidenNumElts - 1 - i;
2264
2265 MVT WidenVT = MVT::getVectorVT(
2266 VT.getVectorElementType() == MVT::i8 ? MVT::i32 : MVT::i64, WidenNumElts);
2267 SDValue NewV1 = DAG.getBitcast(WidenVT, V1);
2268 SDValue WidenRev = DAG.getVectorShuffle(WidenVT, DL, NewV1,
2269 DAG.getUNDEF(WidenVT), WidenMask);
2270
2271 return DAG.getNode(LoongArchISD::VSHUF4I, DL, VT,
2272 DAG.getBitcast(VT, WidenRev),
2273 DAG.getConstant(27, DL, Subtarget.getGRLenVT()));
2274}
2275
2276/// Lower VECTOR_SHUFFLE into VPACKEV (if possible).
2277///
2278/// VPACKEV interleaves the even elements from each vector.
2279///
2280/// It is possible to lower into VPACKEV when the mask consists of two of the
2281/// following forms interleaved:
2282/// <0, 2, 4, ...>
2283/// <n, n+2, n+4, ...>
2284/// where n is the number of elements in the vector.
2285/// For example:
2286/// <0, 0, 2, 2, 4, 4, ...>
2287/// <0, n, 2, n+2, 4, n+4, ...>
2288///
2289/// When undef's appear in the mask they are treated as if they were whatever
2290/// value is necessary in order to fit the above forms.
2292 MVT VT, SDValue V1, SDValue V2,
2293 SelectionDAG &DAG) {
2294
2295 const auto &Begin = Mask.begin();
2296 const auto &End = Mask.end();
2297 SDValue OriV1 = V1, OriV2 = V2;
2298
2299 if (fitsRegularPattern<int>(Begin, 2, End, 0, 2))
2300 V1 = OriV1;
2301 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size(), 2))
2302 V1 = OriV2;
2303 else
2304 return SDValue();
2305
2306 if (fitsRegularPattern<int>(Begin + 1, 2, End, 0, 2))
2307 V2 = OriV1;
2308 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size(), 2))
2309 V2 = OriV2;
2310 else
2311 return SDValue();
2312
2313 return DAG.getNode(LoongArchISD::VPACKEV, DL, VT, V2, V1);
2314}
2315
2316/// Lower VECTOR_SHUFFLE into VPACKOD (if possible).
2317///
2318/// VPACKOD interleaves the odd elements from each vector.
2319///
2320/// It is possible to lower into VPACKOD when the mask consists of two of the
2321/// following forms interleaved:
2322/// <1, 3, 5, ...>
2323/// <n+1, n+3, n+5, ...>
2324/// where n is the number of elements in the vector.
2325/// For example:
2326/// <1, 1, 3, 3, 5, 5, ...>
2327/// <1, n+1, 3, n+3, 5, n+5, ...>
2328///
2329/// When undef's appear in the mask they are treated as if they were whatever
2330/// value is necessary in order to fit the above forms.
2332 MVT VT, SDValue V1, SDValue V2,
2333 SelectionDAG &DAG) {
2334
2335 const auto &Begin = Mask.begin();
2336 const auto &End = Mask.end();
2337 SDValue OriV1 = V1, OriV2 = V2;
2338
2339 if (fitsRegularPattern<int>(Begin, 2, End, 1, 2))
2340 V1 = OriV1;
2341 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size() + 1, 2))
2342 V1 = OriV2;
2343 else
2344 return SDValue();
2345
2346 if (fitsRegularPattern<int>(Begin + 1, 2, End, 1, 2))
2347 V2 = OriV1;
2348 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size() + 1, 2))
2349 V2 = OriV2;
2350 else
2351 return SDValue();
2352
2353 return DAG.getNode(LoongArchISD::VPACKOD, DL, VT, V2, V1);
2354}
2355
2356/// Lower VECTOR_SHUFFLE into VILVH (if possible).
2357///
2358/// VILVH interleaves consecutive elements from the left (highest-indexed) half
2359/// of each vector.
2360///
2361/// It is possible to lower into VILVH when the mask consists of two of the
2362/// following forms interleaved:
2363/// <x, x+1, x+2, ...>
2364/// <n+x, n+x+1, n+x+2, ...>
2365/// where n is the number of elements in the vector and x is half n.
2366/// For example:
2367/// <x, x, x+1, x+1, x+2, x+2, ...>
2368/// <x, n+x, x+1, n+x+1, x+2, n+x+2, ...>
2369///
2370/// When undef's appear in the mask they are treated as if they were whatever
2371/// value is necessary in order to fit the above forms.
2373 MVT VT, SDValue V1, SDValue V2,
2374 SelectionDAG &DAG) {
2375
2376 const auto &Begin = Mask.begin();
2377 const auto &End = Mask.end();
2378 unsigned HalfSize = Mask.size() / 2;
2379 SDValue OriV1 = V1, OriV2 = V2;
2380
2381 if (fitsRegularPattern<int>(Begin, 2, End, HalfSize, 1))
2382 V1 = OriV1;
2383 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size() + HalfSize, 1))
2384 V1 = OriV2;
2385 else
2386 return SDValue();
2387
2388 if (fitsRegularPattern<int>(Begin + 1, 2, End, HalfSize, 1))
2389 V2 = OriV1;
2390 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size() + HalfSize,
2391 1))
2392 V2 = OriV2;
2393 else
2394 return SDValue();
2395
2396 return DAG.getNode(LoongArchISD::VILVH, DL, VT, V2, V1);
2397}
2398
2399/// Lower VECTOR_SHUFFLE into VILVL (if possible).
2400///
2401/// VILVL interleaves consecutive elements from the right (lowest-indexed) half
2402/// of each vector.
2403///
2404/// It is possible to lower into VILVL when the mask consists of two of the
2405/// following forms interleaved:
2406/// <0, 1, 2, ...>
2407/// <n, n+1, n+2, ...>
2408/// where n is the number of elements in the vector.
2409/// For example:
2410/// <0, 0, 1, 1, 2, 2, ...>
2411/// <0, n, 1, n+1, 2, n+2, ...>
2412///
2413/// When undef's appear in the mask they are treated as if they were whatever
2414/// value is necessary in order to fit the above forms.
2416 MVT VT, SDValue V1, SDValue V2,
2417 SelectionDAG &DAG) {
2418
2419 const auto &Begin = Mask.begin();
2420 const auto &End = Mask.end();
2421 SDValue OriV1 = V1, OriV2 = V2;
2422
2423 if (fitsRegularPattern<int>(Begin, 2, End, 0, 1))
2424 V1 = OriV1;
2425 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size(), 1))
2426 V1 = OriV2;
2427 else
2428 return SDValue();
2429
2430 if (fitsRegularPattern<int>(Begin + 1, 2, End, 0, 1))
2431 V2 = OriV1;
2432 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size(), 1))
2433 V2 = OriV2;
2434 else
2435 return SDValue();
2436
2437 return DAG.getNode(LoongArchISD::VILVL, DL, VT, V2, V1);
2438}
2439
2440/// Lower VECTOR_SHUFFLE into VPICKEV (if possible).
2441///
2442/// VPICKEV copies the even elements of each vector into the result vector.
2443///
2444/// It is possible to lower into VPICKEV when the mask consists of two of the
2445/// following forms concatenated:
2446/// <0, 2, 4, ...>
2447/// <n, n+2, n+4, ...>
2448/// where n is the number of elements in the vector.
2449/// For example:
2450/// <0, 2, 4, ..., 0, 2, 4, ...>
2451/// <0, 2, 4, ..., n, n+2, n+4, ...>
2452///
2453/// When undef's appear in the mask they are treated as if they were whatever
2454/// value is necessary in order to fit the above forms.
2456 MVT VT, SDValue V1, SDValue V2,
2457 SelectionDAG &DAG) {
2458
2459 const auto &Begin = Mask.begin();
2460 const auto &Mid = Mask.begin() + Mask.size() / 2;
2461 const auto &End = Mask.end();
2462 SDValue OriV1 = V1, OriV2 = V2;
2463
2464 if (fitsRegularPattern<int>(Begin, 1, Mid, 0, 2))
2465 V1 = OriV1;
2466 else if (fitsRegularPattern<int>(Begin, 1, Mid, Mask.size(), 2))
2467 V1 = OriV2;
2468 else
2469 return SDValue();
2470
2471 if (fitsRegularPattern<int>(Mid, 1, End, 0, 2))
2472 V2 = OriV1;
2473 else if (fitsRegularPattern<int>(Mid, 1, End, Mask.size(), 2))
2474 V2 = OriV2;
2475
2476 else
2477 return SDValue();
2478
2479 return DAG.getNode(LoongArchISD::VPICKEV, DL, VT, V2, V1);
2480}
2481
2482/// Lower VECTOR_SHUFFLE into VPICKOD (if possible).
2483///
2484/// VPICKOD copies the odd elements of each vector into the result vector.
2485///
2486/// It is possible to lower into VPICKOD when the mask consists of two of the
2487/// following forms concatenated:
2488/// <1, 3, 5, ...>
2489/// <n+1, n+3, n+5, ...>
2490/// where n is the number of elements in the vector.
2491/// For example:
2492/// <1, 3, 5, ..., 1, 3, 5, ...>
2493/// <1, 3, 5, ..., n+1, n+3, n+5, ...>
2494///
2495/// When undef's appear in the mask they are treated as if they were whatever
2496/// value is necessary in order to fit the above forms.
2498 MVT VT, SDValue V1, SDValue V2,
2499 SelectionDAG &DAG) {
2500
2501 const auto &Begin = Mask.begin();
2502 const auto &Mid = Mask.begin() + Mask.size() / 2;
2503 const auto &End = Mask.end();
2504 SDValue OriV1 = V1, OriV2 = V2;
2505
2506 if (fitsRegularPattern<int>(Begin, 1, Mid, 1, 2))
2507 V1 = OriV1;
2508 else if (fitsRegularPattern<int>(Begin, 1, Mid, Mask.size() + 1, 2))
2509 V1 = OriV2;
2510 else
2511 return SDValue();
2512
2513 if (fitsRegularPattern<int>(Mid, 1, End, 1, 2))
2514 V2 = OriV1;
2515 else if (fitsRegularPattern<int>(Mid, 1, End, Mask.size() + 1, 2))
2516 V2 = OriV2;
2517 else
2518 return SDValue();
2519
2520 return DAG.getNode(LoongArchISD::VPICKOD, DL, VT, V2, V1);
2521}
2522
2523/// Lower VECTOR_SHUFFLE into VEXTRINS (if possible).
2524///
2525/// VEXTRINS copies one element of a vector into any place of the result
2526/// vector and makes no change to the rest elements of the result vector.
2527///
2528/// It is possible to lower into VEXTRINS when the mask takes the form:
2529/// <0, 1, 2, ..., n+i, ..., n-1> or <n, n+1, n+2, ..., i, ..., 2n-1> or
2530/// <0, 1, 2, ..., i, ..., n-1> or <n, n+1, n+2, ..., n+i, ..., 2n-1>
2531/// where n is the number of elements in the vector and i is in [0, n).
2532/// For example:
2533/// <0, 1, 2, 3, 4, 5, 6, 8> , <2, 9, 10, 11, 12, 13, 14, 15> ,
2534/// <0, 1, 2, 6, 4, 5, 6, 7> , <8, 9, 10, 11, 12, 9, 14, 15>
2535///
2536/// When undef's appear in the mask they are treated as if they were whatever
2537/// value is necessary in order to fit the above forms.
2538static SDValue
2540 SDValue V1, SDValue V2, SelectionDAG &DAG,
2542 unsigned NumElts = VT.getVectorNumElements();
2543 MVT EltVT = VT.getVectorElementType();
2544 MVT GRLenVT = Subtarget.getGRLenVT();
2545
2546 if (Mask.size() != NumElts)
2547 return SDValue();
2548
2549 auto tryLowerToExtrAndIns = [&](unsigned Base) -> SDValue {
2550 int DiffCount = 0;
2551 int DiffPos = -1;
2552 for (unsigned i = 0; i < NumElts; ++i) {
2553 if (Mask[i] == -1)
2554 continue;
2555 if (Mask[i] != int(Base + i)) {
2556 ++DiffCount;
2557 DiffPos = int(i);
2558 if (DiffCount > 1)
2559 return SDValue();
2560 }
2561 }
2562
2563 // Need exactly one differing element to lower into VEXTRINS.
2564 if (DiffCount != 1)
2565 return SDValue();
2566
2567 // DiffMask must be in [0, 2N).
2568 int DiffMask = Mask[DiffPos];
2569 if (DiffMask < 0 || DiffMask >= int(2 * NumElts))
2570 return SDValue();
2571
2572 // Determine source vector and source index.
2573 SDValue SrcVec;
2574 unsigned SrcIdx;
2575 if (unsigned(DiffMask) < NumElts) {
2576 SrcVec = V1;
2577 SrcIdx = unsigned(DiffMask);
2578 } else {
2579 SrcVec = V2;
2580 SrcIdx = unsigned(DiffMask) - NumElts;
2581 }
2582
2583 // Replace with EXTRACT_VECTOR_ELT + INSERT_VECTOR_ELT, it will match the
2584 // patterns of VEXTRINS in tablegen.
2585 SDValue Extracted = DAG.getNode(
2586 ISD::EXTRACT_VECTOR_ELT, DL, EltVT.isFloatingPoint() ? EltVT : GRLenVT,
2587 SrcVec, DAG.getConstant(SrcIdx, DL, GRLenVT));
2588 SDValue Result =
2589 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, (Base == 0) ? V1 : V2,
2590 Extracted, DAG.getConstant(DiffPos, DL, GRLenVT));
2591
2592 return Result;
2593 };
2594
2595 // Try [0, n-1) insertion then [n, 2n-1) insertion.
2596 if (SDValue Result = tryLowerToExtrAndIns(0))
2597 return Result;
2598 return tryLowerToExtrAndIns(NumElts);
2599}
2600
2601// Check the Mask and then build SrcVec and MaskImm infos which will
2602// be used to build LoongArchISD nodes for VPERMI_W or XVPERMI_W.
2603// On success, return true. Otherwise, return false.
2606 unsigned &MaskImm) {
2607 unsigned MaskSize = Mask.size();
2608
2609 auto isValid = [&](int M, int Off) {
2610 return (M == -1) || (M >= Off && M < Off + 4);
2611 };
2612
2613 auto buildImm = [&](int MLo, int MHi, unsigned Off, unsigned I) {
2614 auto immPart = [&](int M, unsigned Off) {
2615 return (M == -1 ? 0 : (M - Off)) & 0x3;
2616 };
2617 MaskImm |= immPart(MLo, Off) << (I * 2);
2618 MaskImm |= immPart(MHi, Off) << ((I + 1) * 2);
2619 };
2620
2621 for (unsigned i = 0; i < 4; i += 2) {
2622 int MLo = Mask[i];
2623 int MHi = Mask[i + 1];
2624
2625 if (MaskSize == 8) { // Only v8i32/v8f32 need this check.
2626 auto isValid2 = [&](int &M, int M2) {
2627 // If high half index is undef, it's always valid.
2628 if (M2 == -1)
2629 return true;
2630 if (M == -1) {
2631 // If low half index is undef, use index from high half,
2632 // remapped to low half.
2633 if ((M2 % MaskSize) < 4)
2634 return false;
2635 M = M2 - 4;
2636 return true;
2637 }
2638 // Index in low half must be same as index in high half.
2639 return M2 == M + 4;
2640 };
2641 if (!isValid2(MLo, Mask[i + 4]) || !isValid2(MHi, Mask[i + 5]))
2642 return false;
2643 }
2644
2645 if (isValid(MLo, 0) && isValid(MHi, 0)) {
2646 SrcVec.push_back(V1);
2647 buildImm(MLo, MHi, 0, i);
2648 } else if (isValid(MLo, MaskSize) && isValid(MHi, MaskSize)) {
2649 SrcVec.push_back(V2);
2650 buildImm(MLo, MHi, MaskSize, i);
2651 } else {
2652 return false;
2653 }
2654 }
2655
2656 return true;
2657}
2658
2659/// Lower VECTOR_SHUFFLE into VPERMI (if possible).
2660///
2661/// VPERMI selects two elements from each of the two vectors based on the
2662/// mask and places them in the corresponding positions of the result vector
2663/// in order. Only v4i32 and v4f32 types are allowed.
2664///
2665/// It is possible to lower into VPERMI when the mask consists of two of the
2666/// following forms concatenated:
2667/// <i, j, u, v>
2668/// <u, v, i, j>
2669/// where i,j are in [0,4) and u,v are in [4, 8).
2670/// For example:
2671/// <2, 3, 4, 5>
2672/// <5, 7, 0, 2>
2673///
2674/// When undef's appear in the mask they are treated as if they were whatever
2675/// value is necessary in order to fit the above forms.
2677 MVT VT, SDValue V1, SDValue V2,
2678 SelectionDAG &DAG,
2680 if ((VT != MVT::v4i32 && VT != MVT::v4f32) ||
2681 Mask.size() != VT.getVectorNumElements())
2682 return SDValue();
2683
2685 unsigned MaskImm = 0;
2686 if (!buildVPERMIInfo(Mask, V1, V2, SrcVec, MaskImm))
2687 return SDValue();
2688
2689 return DAG.getNode(LoongArchISD::VPERMI, DL, VT, SrcVec[1], SrcVec[0],
2690 DAG.getConstant(MaskImm, DL, Subtarget.getGRLenVT()));
2691}
2692
2693/// Lower VECTOR_SHUFFLE into VSHUF.
2694///
2695/// This mostly consists of converting the shuffle mask into a BUILD_VECTOR and
2696/// adding it as an operand to the resulting VSHUF.
2698 MVT VT, SDValue V1, SDValue V2,
2699 SelectionDAG &DAG,
2701
2703 for (auto M : Mask)
2704 Ops.push_back(DAG.getSignedConstant(M, DL, Subtarget.getGRLenVT()));
2705
2706 EVT MaskVecTy = VT.changeVectorElementTypeToInteger();
2707 SDValue MaskVec = DAG.getBuildVector(MaskVecTy, DL, Ops);
2708
2709 // VECTOR_SHUFFLE concatenates the vectors in an vectorwise fashion.
2710 // <0b00, 0b01> + <0b10, 0b11> -> <0b00, 0b01, 0b10, 0b11>
2711 // VSHF concatenates the vectors in a bitwise fashion:
2712 // <0b00, 0b01> + <0b10, 0b11> ->
2713 // 0b0100 + 0b1110 -> 0b01001110
2714 // <0b10, 0b11, 0b00, 0b01>
2715 // We must therefore swap the operands to get the correct result.
2716 return DAG.getNode(LoongArchISD::VSHUF, DL, VT, MaskVec, V2, V1);
2717}
2718
2719/// Dispatching routine to lower various 128-bit LoongArch vector shuffles.
2720///
2721/// This routine breaks down the specific type of 128-bit shuffle and
2722/// dispatches to the lowering routines accordingly.
2724 SDValue V1, SDValue V2, SelectionDAG &DAG,
2726 assert((VT.SimpleTy == MVT::v16i8 || VT.SimpleTy == MVT::v8i16 ||
2727 VT.SimpleTy == MVT::v4i32 || VT.SimpleTy == MVT::v2i64 ||
2728 VT.SimpleTy == MVT::v4f32 || VT.SimpleTy == MVT::v2f64) &&
2729 "Vector type is unsupported for lsx!");
2730 assert(V1.getSimpleValueType() == V2.getSimpleValueType() &&
2731 "Two operands have different types!");
2732 assert(VT.getVectorNumElements() == Mask.size() &&
2733 "Unexpected mask size for shuffle!");
2734 assert(Mask.size() % 2 == 0 && "Expected even mask size.");
2735
2736 APInt KnownUndef, KnownZero;
2737 computeZeroableShuffleElements(Mask, V1, V2, KnownUndef, KnownZero);
2738 APInt Zeroable = KnownUndef | KnownZero;
2739
2740 SDValue Result;
2741 // TODO: Add more comparison patterns.
2742 if (V2.isUndef()) {
2743 if ((Result =
2744 lowerVECTOR_SHUFFLE_VREPLVEI(DL, Mask, VT, V1, DAG, Subtarget)))
2745 return Result;
2746 if ((Result =
2747 lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2748 return Result;
2749 if ((Result =
2750 lowerVECTOR_SHUFFLE_IsReverse(DL, Mask, VT, V1, DAG, Subtarget)))
2751 return Result;
2752
2753 // TODO: This comment may be enabled in the future to better match the
2754 // pattern for instruction selection.
2755 /* V2 = V1; */
2756 }
2757
2758 // It is recommended not to change the pattern comparison order for better
2759 // performance.
2760 if ((Result = lowerVECTOR_SHUFFLE_VPACKEV(DL, Mask, VT, V1, V2, DAG)))
2761 return Result;
2762 if ((Result = lowerVECTOR_SHUFFLE_VPACKOD(DL, Mask, VT, V1, V2, DAG)))
2763 return Result;
2764 if ((Result = lowerVECTOR_SHUFFLE_VILVH(DL, Mask, VT, V1, V2, DAG)))
2765 return Result;
2766 if ((Result = lowerVECTOR_SHUFFLE_VILVL(DL, Mask, VT, V1, V2, DAG)))
2767 return Result;
2768 if ((Result = lowerVECTOR_SHUFFLE_VPICKEV(DL, Mask, VT, V1, V2, DAG)))
2769 return Result;
2770 if ((Result = lowerVECTOR_SHUFFLE_VPICKOD(DL, Mask, VT, V1, V2, DAG)))
2771 return Result;
2772 if ((VT.SimpleTy == MVT::v2i64 || VT.SimpleTy == MVT::v2f64) &&
2773 (Result =
2774 lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2775 return Result;
2776 if ((Result =
2777 lowerVECTOR_SHUFFLE_VEXTRINS(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2778 return Result;
2779 if ((Result = lowerVECTOR_SHUFFLEAsShift(DL, Mask, VT, V1, V2, DAG, Subtarget,
2780 Zeroable)))
2781 return Result;
2782 if ((Result =
2783 lowerVECTOR_SHUFFLE_VPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2784 return Result;
2785 if ((Result = lowerVECTOR_SHUFFLEAsZeroOrAnyExtend(DL, Mask, VT, V1, V2, DAG,
2786 Zeroable)))
2787 return Result;
2788 if ((Result = lowerVECTOR_SHUFFLEAsByteRotate(DL, Mask, VT, V1, V2, DAG,
2789 Subtarget)))
2790 return Result;
2791 if (SDValue NewShuffle = widenShuffleMask(DL, Mask, VT, V1, V2, DAG))
2792 return NewShuffle;
2793 if ((Result =
2794 lowerVECTOR_SHUFFLE_VSHUF(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2795 return Result;
2796 return SDValue();
2797}
2798
2799/// Lower VECTOR_SHUFFLE into XVREPLVEI (if possible).
2800///
2801/// It is a XVREPLVEI when the mask is:
2802/// <x, x, x, ..., x+n, x+n, x+n, ...>
2803/// where the number of x is equal to n and n is half the length of vector.
2804///
2805/// When undef's appear in the mask they are treated as if they were whatever
2806/// value is necessary in order to fit the above form.
2807static SDValue
2809 SDValue V1, SelectionDAG &DAG,
2811 int SplatIndex = -1;
2812 for (const auto &M : Mask) {
2813 if (M != -1) {
2814 SplatIndex = M;
2815 break;
2816 }
2817 }
2818
2819 if (SplatIndex == -1)
2820 return DAG.getUNDEF(VT);
2821
2822 const auto &Begin = Mask.begin();
2823 const auto &End = Mask.end();
2824 int HalfSize = Mask.size() / 2;
2825
2826 if (SplatIndex >= HalfSize)
2827 return SDValue();
2828
2829 assert(SplatIndex < (int)Mask.size() && "Out of bounds mask index");
2830 if (fitsRegularPattern<int>(Begin, 1, End - HalfSize, SplatIndex, 0) &&
2831 fitsRegularPattern<int>(Begin + HalfSize, 1, End, SplatIndex + HalfSize,
2832 0)) {
2833 return DAG.getNode(LoongArchISD::VREPLVEI, DL, VT, V1,
2834 DAG.getConstant(SplatIndex, DL, Subtarget.getGRLenVT()));
2835 }
2836
2837 return SDValue();
2838}
2839
2840/// Lower VECTOR_SHUFFLE into XVSHUF4I (if possible).
2841static SDValue
2843 SDValue V1, SDValue V2, SelectionDAG &DAG,
2845 // XVSHUF4I_D must be handled separately because it is different from other
2846 // types of [X]VSHUF4I instructions.
2847 if (Mask.size() == 4) {
2848 unsigned MaskImm = 0;
2849 for (int i = 1; i >= 0; --i) {
2850 int MLo = Mask[i];
2851 int MHi = Mask[i + 2];
2852 if (!(MLo == -1 || (MLo >= 0 && MLo <= 1) || (MLo >= 4 && MLo <= 5)) ||
2853 !(MHi == -1 || (MHi >= 2 && MHi <= 3) || (MHi >= 6 && MHi <= 7)))
2854 return SDValue();
2855 if (MHi != -1 && MLo != -1 && MHi != MLo + 2)
2856 return SDValue();
2857
2858 MaskImm <<= 2;
2859 if (MLo != -1)
2860 MaskImm |= ((MLo <= 1) ? MLo : (MLo - 2)) & 0x3;
2861 else if (MHi != -1)
2862 MaskImm |= ((MHi <= 3) ? (MHi - 2) : (MHi - 4)) & 0x3;
2863 }
2864
2865 return DAG.getNode(LoongArchISD::VSHUF4I_D, DL, VT, V1, V2,
2866 DAG.getConstant(MaskImm, DL, Subtarget.getGRLenVT()));
2867 }
2868
2869 return lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget);
2870}
2871
2872/// Lower VECTOR_SHUFFLE into XVREPLVE0 (if possible).
2873///
2874/// It is a XVREPLVE0 when the VECTOR_SHUFFLE is a broadcast of element 0,
2875/// i.e. the mask is:
2876/// <0, 0, 0, ...>
2877///
2878/// When undef's appear in the mask they are treated as if they were whatever
2879/// value is necessary in order to fit the above form.
2881 ArrayRef<int> Mask, MVT VT,
2882 SDValue V1, SelectionDAG &DAG) {
2883 if (!ShuffleVectorInst::isZeroEltSplatMask(Mask, Mask.size()))
2884 return SDValue();
2885
2886 return DAG.getNode(LoongArchISD::XVREPLVE0, DL, VT, V1);
2887}
2888
2889/// Lower VECTOR_SHUFFLE into XVPERMI (if possible).
2890static SDValue
2892 SDValue V1, SDValue V2, SelectionDAG &DAG,
2894 MVT GRLenVT = Subtarget.getGRLenVT();
2895 unsigned MaskSize = Mask.size();
2896 if (MaskSize != VT.getVectorNumElements())
2897 return SDValue();
2898
2899 // Consider XVPERMI_W.
2900 if (VT == MVT::v8i32 || VT == MVT::v8f32) {
2902 unsigned MaskImm = 0;
2903 if (!buildVPERMIInfo(Mask, V1, V2, SrcVec, MaskImm))
2904 return SDValue();
2905
2906 return DAG.getNode(LoongArchISD::VPERMI, DL, VT, SrcVec[1], SrcVec[0],
2907 DAG.getConstant(MaskImm, DL, GRLenVT));
2908 }
2909
2910 // Consider XVPERMI_D.
2911 if (VT == MVT::v4i64 || VT == MVT::v4f64) {
2912 unsigned MaskImm = 0;
2913 for (unsigned i = 0; i < MaskSize; ++i) {
2914 if (Mask[i] == -1)
2915 continue;
2916 if (Mask[i] >= (int)MaskSize)
2917 return SDValue();
2918 MaskImm |= Mask[i] << (i * 2);
2919 }
2920
2921 return DAG.getNode(LoongArchISD::XVPERMI, DL, VT, V1,
2922 DAG.getConstant(MaskImm, DL, GRLenVT));
2923 }
2924
2925 return SDValue();
2926}
2927
2928/// Lower VECTOR_SHUFFLE into XVPERM (if possible).
2930 MVT VT, SDValue V1, SelectionDAG &DAG,
2932 // LoongArch LASX only have XVPERM_W.
2933 if (Mask.size() != 8 || (VT != MVT::v8i32 && VT != MVT::v8f32))
2934 return SDValue();
2935
2936 unsigned NumElts = VT.getVectorNumElements();
2937 unsigned HalfSize = NumElts / 2;
2938 bool FrontLo = true, FrontHi = true;
2939 bool BackLo = true, BackHi = true;
2940
2941 auto inRange = [](int val, int low, int high) {
2942 return (val == -1) || (val >= low && val < high);
2943 };
2944
2945 for (unsigned i = 0; i < HalfSize; ++i) {
2946 int Fronti = Mask[i];
2947 int Backi = Mask[i + HalfSize];
2948
2949 FrontLo &= inRange(Fronti, 0, HalfSize);
2950 FrontHi &= inRange(Fronti, HalfSize, NumElts);
2951 BackLo &= inRange(Backi, 0, HalfSize);
2952 BackHi &= inRange(Backi, HalfSize, NumElts);
2953 }
2954
2955 // If both the lower and upper 128-bit parts access only one half of the
2956 // vector (either lower or upper), avoid using xvperm.w. The latency of
2957 // xvperm.w(3) is higher than using xvshuf(1) and xvori(1).
2958 if ((FrontLo || FrontHi) && (BackLo || BackHi))
2959 return SDValue();
2960
2962 MVT GRLenVT = Subtarget.getGRLenVT();
2963 for (unsigned i = 0; i < NumElts; ++i)
2964 Masks.push_back(Mask[i] == -1 ? DAG.getUNDEF(GRLenVT)
2965 : DAG.getConstant(Mask[i], DL, GRLenVT));
2966 SDValue MaskVec = DAG.getBuildVector(MVT::v8i32, DL, Masks);
2967
2968 return DAG.getNode(LoongArchISD::XVPERM, DL, VT, V1, MaskVec);
2969}
2970
2971/// Lower VECTOR_SHUFFLE into XVPACKEV (if possible).
2973 MVT VT, SDValue V1, SDValue V2,
2974 SelectionDAG &DAG) {
2975 return lowerVECTOR_SHUFFLE_VPACKEV(DL, Mask, VT, V1, V2, DAG);
2976}
2977
2978/// Lower VECTOR_SHUFFLE into XVPACKOD (if possible).
2980 MVT VT, SDValue V1, SDValue V2,
2981 SelectionDAG &DAG) {
2982 return lowerVECTOR_SHUFFLE_VPACKOD(DL, Mask, VT, V1, V2, DAG);
2983}
2984
2985/// Lower VECTOR_SHUFFLE into XVILVH (if possible).
2987 MVT VT, SDValue V1, SDValue V2,
2988 SelectionDAG &DAG) {
2989
2990 const auto &Begin = Mask.begin();
2991 const auto &End = Mask.end();
2992 unsigned HalfSize = Mask.size() / 2;
2993 unsigned LeftSize = HalfSize / 2;
2994 SDValue OriV1 = V1, OriV2 = V2;
2995
2996 if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, HalfSize - LeftSize,
2997 1) &&
2998 fitsRegularPattern<int>(Begin + HalfSize, 2, End, HalfSize + LeftSize, 1))
2999 V1 = OriV1;
3000 else if (fitsRegularPattern<int>(Begin, 2, End - HalfSize,
3001 Mask.size() + HalfSize - LeftSize, 1) &&
3002 fitsRegularPattern<int>(Begin + HalfSize, 2, End,
3003 Mask.size() + HalfSize + LeftSize, 1))
3004 V1 = OriV2;
3005 else
3006 return SDValue();
3007
3008 if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, HalfSize - LeftSize,
3009 1) &&
3010 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End, HalfSize + LeftSize,
3011 1))
3012 V2 = OriV1;
3013 else if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize,
3014 Mask.size() + HalfSize - LeftSize, 1) &&
3015 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End,
3016 Mask.size() + HalfSize + LeftSize, 1))
3017 V2 = OriV2;
3018 else
3019 return SDValue();
3020
3021 return DAG.getNode(LoongArchISD::VILVH, DL, VT, V2, V1);
3022}
3023
3024/// Lower VECTOR_SHUFFLE into XVILVL (if possible).
3026 MVT VT, SDValue V1, SDValue V2,
3027 SelectionDAG &DAG) {
3028
3029 const auto &Begin = Mask.begin();
3030 const auto &End = Mask.end();
3031 unsigned HalfSize = Mask.size() / 2;
3032 SDValue OriV1 = V1, OriV2 = V2;
3033
3034 if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, 0, 1) &&
3035 fitsRegularPattern<int>(Begin + HalfSize, 2, End, HalfSize, 1))
3036 V1 = OriV1;
3037 else if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, Mask.size(), 1) &&
3038 fitsRegularPattern<int>(Begin + HalfSize, 2, End,
3039 Mask.size() + HalfSize, 1))
3040 V1 = OriV2;
3041 else
3042 return SDValue();
3043
3044 if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, 0, 1) &&
3045 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End, HalfSize, 1))
3046 V2 = OriV1;
3047 else if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, Mask.size(),
3048 1) &&
3049 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End,
3050 Mask.size() + HalfSize, 1))
3051 V2 = OriV2;
3052 else
3053 return SDValue();
3054
3055 return DAG.getNode(LoongArchISD::VILVL, DL, VT, V2, V1);
3056}
3057
3058/// Lower VECTOR_SHUFFLE into XVPICKEV (if possible).
3060 MVT VT, SDValue V1, SDValue V2,
3061 SelectionDAG &DAG) {
3062
3063 const auto &Begin = Mask.begin();
3064 const auto &LeftMid = Mask.begin() + Mask.size() / 4;
3065 const auto &Mid = Mask.begin() + Mask.size() / 2;
3066 const auto &RightMid = Mask.end() - Mask.size() / 4;
3067 const auto &End = Mask.end();
3068 unsigned HalfSize = Mask.size() / 2;
3069 SDValue OriV1 = V1, OriV2 = V2;
3070
3071 if (fitsRegularPattern<int>(Begin, 1, LeftMid, 0, 2) &&
3072 fitsRegularPattern<int>(Mid, 1, RightMid, HalfSize, 2))
3073 V1 = OriV1;
3074 else if (fitsRegularPattern<int>(Begin, 1, LeftMid, Mask.size(), 2) &&
3075 fitsRegularPattern<int>(Mid, 1, RightMid, Mask.size() + HalfSize, 2))
3076 V1 = OriV2;
3077 else
3078 return SDValue();
3079
3080 if (fitsRegularPattern<int>(LeftMid, 1, Mid, 0, 2) &&
3081 fitsRegularPattern<int>(RightMid, 1, End, HalfSize, 2))
3082 V2 = OriV1;
3083 else if (fitsRegularPattern<int>(LeftMid, 1, Mid, Mask.size(), 2) &&
3084 fitsRegularPattern<int>(RightMid, 1, End, Mask.size() + HalfSize, 2))
3085 V2 = OriV2;
3086
3087 else
3088 return SDValue();
3089
3090 return DAG.getNode(LoongArchISD::VPICKEV, DL, VT, V2, V1);
3091}
3092
3093/// Lower VECTOR_SHUFFLE into XVPICKOD (if possible).
3095 MVT VT, SDValue V1, SDValue V2,
3096 SelectionDAG &DAG) {
3097
3098 const auto &Begin = Mask.begin();
3099 const auto &LeftMid = Mask.begin() + Mask.size() / 4;
3100 const auto &Mid = Mask.begin() + Mask.size() / 2;
3101 const auto &RightMid = Mask.end() - Mask.size() / 4;
3102 const auto &End = Mask.end();
3103 unsigned HalfSize = Mask.size() / 2;
3104 SDValue OriV1 = V1, OriV2 = V2;
3105
3106 if (fitsRegularPattern<int>(Begin, 1, LeftMid, 1, 2) &&
3107 fitsRegularPattern<int>(Mid, 1, RightMid, HalfSize + 1, 2))
3108 V1 = OriV1;
3109 else if (fitsRegularPattern<int>(Begin, 1, LeftMid, Mask.size() + 1, 2) &&
3110 fitsRegularPattern<int>(Mid, 1, RightMid, Mask.size() + HalfSize + 1,
3111 2))
3112 V1 = OriV2;
3113 else
3114 return SDValue();
3115
3116 if (fitsRegularPattern<int>(LeftMid, 1, Mid, 1, 2) &&
3117 fitsRegularPattern<int>(RightMid, 1, End, HalfSize + 1, 2))
3118 V2 = OriV1;
3119 else if (fitsRegularPattern<int>(LeftMid, 1, Mid, Mask.size() + 1, 2) &&
3120 fitsRegularPattern<int>(RightMid, 1, End, Mask.size() + HalfSize + 1,
3121 2))
3122 V2 = OriV2;
3123 else
3124 return SDValue();
3125
3126 return DAG.getNode(LoongArchISD::VPICKOD, DL, VT, V2, V1);
3127}
3128
3129/// Lower VECTOR_SHUFFLE into XVEXTRINS (if possible).
3130static SDValue
3132 SDValue V1, SDValue V2, SelectionDAG &DAG,
3134 int NumElts = VT.getVectorNumElements();
3135 int HalfSize = NumElts / 2;
3136 MVT EltVT = VT.getVectorElementType();
3137 MVT GRLenVT = Subtarget.getGRLenVT();
3138
3139 if ((int)Mask.size() != NumElts)
3140 return SDValue();
3141
3142 auto tryLowerToExtrAndIns = [&](int Base) -> SDValue {
3143 SmallVector<int> DiffPos;
3144 for (int i = 0; i < NumElts; ++i) {
3145 if (Mask[i] == -1)
3146 continue;
3147 if (Mask[i] != Base + i) {
3148 DiffPos.push_back(i);
3149 if (DiffPos.size() > 2)
3150 return SDValue();
3151 }
3152 }
3153
3154 // Need exactly two differing element to lower into XVEXTRINS.
3155 // If only one differing element, the element at a distance of
3156 // HalfSize from it must be undef.
3157 if (DiffPos.size() == 1) {
3158 if (DiffPos[0] < HalfSize && Mask[DiffPos[0] + HalfSize] == -1)
3159 DiffPos.push_back(DiffPos[0] + HalfSize);
3160 else if (DiffPos[0] >= HalfSize && Mask[DiffPos[0] - HalfSize] == -1)
3161 DiffPos.insert(DiffPos.begin(), DiffPos[0] - HalfSize);
3162 else
3163 return SDValue();
3164 }
3165 if (DiffPos.size() != 2 || DiffPos[1] != DiffPos[0] + HalfSize)
3166 return SDValue();
3167
3168 // DiffMask must be in its low or high part.
3169 int DiffMaskLo = Mask[DiffPos[0]];
3170 int DiffMaskHi = Mask[DiffPos[1]];
3171 DiffMaskLo = DiffMaskLo == -1 ? DiffMaskHi - HalfSize : DiffMaskLo;
3172 DiffMaskHi = DiffMaskHi == -1 ? DiffMaskLo + HalfSize : DiffMaskHi;
3173 if (!(DiffMaskLo >= 0 && DiffMaskLo < HalfSize) &&
3174 !(DiffMaskLo >= NumElts && DiffMaskLo < NumElts + HalfSize))
3175 return SDValue();
3176 if (!(DiffMaskHi >= HalfSize && DiffMaskHi < NumElts) &&
3177 !(DiffMaskHi >= NumElts + HalfSize && DiffMaskHi < 2 * NumElts))
3178 return SDValue();
3179 if (DiffMaskHi != DiffMaskLo + HalfSize)
3180 return SDValue();
3181
3182 // Determine source vector and source index.
3183 SDValue SrcVec = (DiffMaskLo < HalfSize) ? V1 : V2;
3184 int SrcIdxLo =
3185 (DiffMaskLo < HalfSize) ? DiffMaskLo : (DiffMaskLo - NumElts);
3186 bool IsEltFP = EltVT.isFloatingPoint();
3187
3188 // Replace with 2*EXTRACT_VECTOR_ELT + 2*INSERT_VECTOR_ELT, it will match
3189 // the patterns of XVEXTRINS in tablegen.
3190 SDValue BaseVec = (Base == 0) ? V1 : V2;
3191 SDValue EltLo =
3192 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IsEltFP ? EltVT : GRLenVT,
3193 SrcVec, DAG.getConstant(SrcIdxLo, DL, GRLenVT));
3194 SDValue InsLo = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, BaseVec, EltLo,
3195 DAG.getConstant(DiffPos[0], DL, GRLenVT));
3196 SDValue EltHi =
3197 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IsEltFP ? EltVT : GRLenVT,
3198 SrcVec, DAG.getConstant(SrcIdxLo + HalfSize, DL, GRLenVT));
3199 SDValue Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, InsLo, EltHi,
3200 DAG.getConstant(DiffPos[1], DL, GRLenVT));
3201
3202 return Result;
3203 };
3204
3205 // Try [0, n-1) insertion then [n, 2n-1) insertion.
3206 if (SDValue Result = tryLowerToExtrAndIns(0))
3207 return Result;
3208 return tryLowerToExtrAndIns(NumElts);
3209}
3210
3211/// Lower VECTOR_SHUFFLE into XVINSVE0 (if possible).
3212static SDValue
3214 SDValue V1, SDValue V2, SelectionDAG &DAG,
3216 // LoongArch LASX only supports xvinsve0.{w/d}.
3217 if (VT != MVT::v8i32 && VT != MVT::v8f32 && VT != MVT::v4i64 &&
3218 VT != MVT::v4f64)
3219 return SDValue();
3220
3221 MVT GRLenVT = Subtarget.getGRLenVT();
3222 int MaskSize = Mask.size();
3223 assert(MaskSize == (int)VT.getVectorNumElements() && "Unexpected mask size");
3224
3225 // Check if exactly one element of the Mask is replaced by 'Replaced', while
3226 // all other elements are either 'Base + i' or undef (-1). On success, return
3227 // the index of the replaced element. Otherwise, just return -1.
3228 auto checkReplaceOne = [&](int Base, int Replaced) -> int {
3229 int Idx = -1;
3230 for (int i = 0; i < MaskSize; ++i) {
3231 if (Mask[i] == Base + i || Mask[i] == -1)
3232 continue;
3233 if (Mask[i] != Replaced)
3234 return -1;
3235 if (Idx == -1)
3236 Idx = i;
3237 else
3238 return -1;
3239 }
3240 return Idx;
3241 };
3242
3243 // Case 1: the lowest element of V2 replaces one element in V1.
3244 int Idx = checkReplaceOne(0, MaskSize);
3245 if (Idx != -1)
3246 return DAG.getNode(LoongArchISD::XVINSVE0, DL, VT, V1, V2,
3247 DAG.getConstant(Idx, DL, GRLenVT));
3248
3249 // Case 2: the lowest element of V1 replaces one element in V2.
3250 Idx = checkReplaceOne(MaskSize, 0);
3251 if (Idx != -1)
3252 return DAG.getNode(LoongArchISD::XVINSVE0, DL, VT, V2, V1,
3253 DAG.getConstant(Idx, DL, GRLenVT));
3254
3255 return SDValue();
3256}
3257
3258/// Lower VECTOR_SHUFFLE into XVSHUF (if possible).
3260 MVT VT, SDValue V1, SDValue V2,
3261 SelectionDAG &DAG) {
3262
3263 int MaskSize = Mask.size();
3264 int HalfSize = Mask.size() / 2;
3265 const auto &Begin = Mask.begin();
3266 const auto &Mid = Mask.begin() + HalfSize;
3267 const auto &End = Mask.end();
3268
3269 // VECTOR_SHUFFLE concatenates the vectors:
3270 // <0, 1, 2, 3, 4, 5, 6, 7> + <8, 9, 10, 11, 12, 13, 14, 15>
3271 // shuffling ->
3272 // <0, 1, 2, 3, 8, 9, 10, 11> <4, 5, 6, 7, 12, 13, 14, 15>
3273 //
3274 // XVSHUF concatenates the vectors:
3275 // <a0, a1, a2, a3, b0, b1, b2, b3> + <a4, a5, a6, a7, b4, b5, b6, b7>
3276 // shuffling ->
3277 // <a0, a1, a2, a3, a4, a5, a6, a7> + <b0, b1, b2, b3, b4, b5, b6, b7>
3278 SmallVector<SDValue, 8> MaskAlloc;
3279 for (auto it = Begin; it < Mid; it++) {
3280 if (*it < 0) // UNDEF
3281 MaskAlloc.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3282 else if ((*it >= 0 && *it < HalfSize) ||
3283 (*it >= MaskSize && *it < MaskSize + HalfSize)) {
3284 int M = *it < HalfSize ? *it : *it - HalfSize;
3285 MaskAlloc.push_back(DAG.getTargetConstant(M, DL, MVT::i64));
3286 } else
3287 return SDValue();
3288 }
3289 assert((int)MaskAlloc.size() == HalfSize && "xvshuf convert failed!");
3290
3291 for (auto it = Mid; it < End; it++) {
3292 if (*it < 0) // UNDEF
3293 MaskAlloc.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3294 else if ((*it >= HalfSize && *it < MaskSize) ||
3295 (*it >= MaskSize + HalfSize && *it < MaskSize * 2)) {
3296 int M = *it < MaskSize ? *it - HalfSize : *it - MaskSize;
3297 MaskAlloc.push_back(DAG.getTargetConstant(M, DL, MVT::i64));
3298 } else
3299 return SDValue();
3300 }
3301 assert((int)MaskAlloc.size() == MaskSize && "xvshuf convert failed!");
3302
3303 EVT MaskVecTy = VT.changeVectorElementTypeToInteger();
3304 SDValue MaskVec = DAG.getBuildVector(MaskVecTy, DL, MaskAlloc);
3305 return DAG.getNode(LoongArchISD::VSHUF, DL, VT, MaskVec, V2, V1);
3306}
3307
3308/// Shuffle vectors by lane to generate more optimized instructions.
3309/// 256-bit shuffles are always considered as 2-lane 128-bit shuffles.
3310///
3311/// Therefore, except for the following four cases, other cases are regarded
3312/// as cross-lane shuffles, where optimization is relatively limited.
3313///
3314/// - Shuffle high, low lanes of two inputs vector
3315/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <0, 5, 3, 6>
3316/// - Shuffle low, high lanes of two inputs vector
3317/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <3, 6, 0, 5>
3318/// - Shuffle low, low lanes of two inputs vector
3319/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <3, 6, 3, 6>
3320/// - Shuffle high, high lanes of two inputs vector
3321/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <0, 5, 0, 5>
3322///
3323/// The first case is the closest to LoongArch instructions and the other
3324/// cases need to be converted to it for processing.
3325///
3326/// This function will return true for the last three cases above and will
3327/// modify V1, V2 and Mask. Otherwise, return false for the first case and
3328/// cross-lane shuffle cases.
3330 const SDLoc &DL, MutableArrayRef<int> Mask, MVT VT, SDValue &V1,
3332
3333 enum HalfMaskType { HighLaneTy, LowLaneTy, None };
3334
3335 int MaskSize = Mask.size();
3336 int HalfSize = Mask.size() / 2;
3337 MVT GRLenVT = Subtarget.getGRLenVT();
3338
3339 HalfMaskType preMask = None, postMask = None;
3340
3341 if (std::all_of(Mask.begin(), Mask.begin() + HalfSize, [&](int M) {
3342 return M < 0 || (M >= 0 && M < HalfSize) ||
3343 (M >= MaskSize && M < MaskSize + HalfSize);
3344 }))
3345 preMask = HighLaneTy;
3346 else if (std::all_of(Mask.begin(), Mask.begin() + HalfSize, [&](int M) {
3347 return M < 0 || (M >= HalfSize && M < MaskSize) ||
3348 (M >= MaskSize + HalfSize && M < MaskSize * 2);
3349 }))
3350 preMask = LowLaneTy;
3351
3352 if (std::all_of(Mask.begin() + HalfSize, Mask.end(), [&](int M) {
3353 return M < 0 || (M >= HalfSize && M < MaskSize) ||
3354 (M >= MaskSize + HalfSize && M < MaskSize * 2);
3355 }))
3356 postMask = LowLaneTy;
3357 else if (std::all_of(Mask.begin() + HalfSize, Mask.end(), [&](int M) {
3358 return M < 0 || (M >= 0 && M < HalfSize) ||
3359 (M >= MaskSize && M < MaskSize + HalfSize);
3360 }))
3361 postMask = HighLaneTy;
3362
3363 // The pre-half of mask is high lane type, and the post-half of mask
3364 // is low lane type, which is closest to the LoongArch instructions.
3365 //
3366 // Note: In the LoongArch architecture, the high lane of mask corresponds
3367 // to the lower 128-bit of vector register, and the low lane of mask
3368 // corresponds the higher 128-bit of vector register.
3369 if (preMask == HighLaneTy && postMask == LowLaneTy) {
3370 return false;
3371 }
3372 if (preMask == LowLaneTy && postMask == HighLaneTy) {
3373 V1 = DAG.getBitcast(MVT::v4i64, V1);
3374 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3375 DAG.getConstant(0b01001110, DL, GRLenVT));
3376 V1 = DAG.getBitcast(VT, V1);
3377
3378 if (!V2.isUndef()) {
3379 V2 = DAG.getBitcast(MVT::v4i64, V2);
3380 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3381 DAG.getConstant(0b01001110, DL, GRLenVT));
3382 V2 = DAG.getBitcast(VT, V2);
3383 }
3384
3385 for (auto it = Mask.begin(); it < Mask.begin() + HalfSize; it++) {
3386 *it = *it < 0 ? *it : *it - HalfSize;
3387 }
3388 for (auto it = Mask.begin() + HalfSize; it < Mask.end(); it++) {
3389 *it = *it < 0 ? *it : *it + HalfSize;
3390 }
3391 } else if (preMask == LowLaneTy && postMask == LowLaneTy) {
3392 V1 = DAG.getBitcast(MVT::v4i64, V1);
3393 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3394 DAG.getConstant(0b11101110, DL, GRLenVT));
3395 V1 = DAG.getBitcast(VT, V1);
3396
3397 if (!V2.isUndef()) {
3398 V2 = DAG.getBitcast(MVT::v4i64, V2);
3399 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3400 DAG.getConstant(0b11101110, DL, GRLenVT));
3401 V2 = DAG.getBitcast(VT, V2);
3402 }
3403
3404 for (auto it = Mask.begin(); it < Mask.begin() + HalfSize; it++) {
3405 *it = *it < 0 ? *it : *it - HalfSize;
3406 }
3407 } else if (preMask == HighLaneTy && postMask == HighLaneTy) {
3408 V1 = DAG.getBitcast(MVT::v4i64, V1);
3409 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3410 DAG.getConstant(0b01000100, DL, GRLenVT));
3411 V1 = DAG.getBitcast(VT, V1);
3412
3413 if (!V2.isUndef()) {
3414 V2 = DAG.getBitcast(MVT::v4i64, V2);
3415 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3416 DAG.getConstant(0b01000100, DL, GRLenVT));
3417 V2 = DAG.getBitcast(VT, V2);
3418 }
3419
3420 for (auto it = Mask.begin() + HalfSize; it < Mask.end(); it++) {
3421 *it = *it < 0 ? *it : *it + HalfSize;
3422 }
3423 } else { // cross-lane
3424 return false;
3425 }
3426
3427 return true;
3428}
3429
3430/// Lower VECTOR_SHUFFLE into XVPERMI_Q (if possible).
3431///
3432/// For example:
3433/// %2 = shufflevector <4 x i64> %0, <4 x i64> %1,
3434/// <4 x i32> <i32 2, i32 3, i32 4, i32 5>
3435/// is lowered to:
3436/// (XVPERMI_Q $xr1, $xr0, 33)
3437static SDValue
3439 SDValue V1, SDValue V2, SelectionDAG &DAG,
3441 // Each 128-bit lane of the result must be a whole lane of V1 or V2.
3442 SmallVector<int, 2> LaneMask;
3443 if (!widenShuffleMaskElts(Mask.size() / 2, Mask, LaneMask))
3444 return SDValue();
3445
3446 // Lanes 0-3 are V1.lo, V1.hi, V2.lo and V2.hi, the same as the XVPERMI_Q
3447 // selector with xj = V1 and xd = V2.
3448 int Lo = LaneMask[0] < 0 ? 0 : LaneMask[0];
3449 int Hi = LaneMask[1] < 0 ? 1 : LaneMask[1];
3450 return DAG.getNode(
3451 LoongArchISD::XVPERMIQ, DL, VT, V2, V1,
3452 DAG.getConstant(Lo | (Hi << 4), DL, Subtarget.getGRLenVT()));
3453}
3454
3455/// Lower VECTOR_SHUFFLE as lane permute and then shuffle (if possible).
3456/// Only for 256-bit vector.
3457///
3458/// Each 128-bit lane of the result may use at most two lanes of the inputs.
3459/// These lanes are first moved into place, then shuffled within the lane.
3460///
3461/// For example:
3462/// %2 = shufflevector <4 x i64> %0, <4 x i64> posion,
3463/// <4 x i64> <i32 0, i32 3, i32 2, i32 0>
3464/// is lowerded to:
3465/// (XVPERMI $xr2, $xr0, 78)
3466/// (XVSHUF $xr1, $xr2, $xr0)
3467/// (XVORI $xr0, $xr1, 0)
3468///
3469/// and the splice:
3470/// %2 = shufflevector <8 x i32> %0, <8 x i32> %1,
3471/// <8 x i32> <i32 7, i32 8, i32 9, i32 10,
3472/// i32 11, i32 12, i32 13, i32 14>
3473/// is lowered to:
3474/// (XVBSLL_V $xr2, $xr1, 4)
3475/// (XVPERMI_Q $xr1, $xr0, 33)
3476/// (XVBSRL_V $xr0, $xr1, 12)
3477/// (XVOR_V $xr0, $xr2, $xr0)
3479 ArrayRef<int> Mask,
3480 MVT VT, SDValue V1,
3481 SDValue V2,
3482 SelectionDAG &DAG) {
3483 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
3484 int Size = Mask.size();
3485 int LaneSize = Size / 2;
3486
3487 // For each result lane, the input lanes (0/1: V1, 2/3: V2) used by the two
3488 // operands of the in-lane shuffle.
3489 int LaneSrcs[2][2] = {{-1, -1}, {-1, -1}};
3490 SmallVector<int, 32> InLaneMask(Size, -1);
3491 bool LaneCrossing = false;
3492 for (int i = 0; i < Size; ++i) {
3493 int M = Mask[i];
3494 if (M < 0)
3495 continue;
3496 int Lane = i / LaneSize;
3497 int SrcLane = M / LaneSize;
3498
3499 // Put lanes that stay in place in the first operand and the others in the
3500 // second one, so a single input becomes V1 and V1 with lanes swapped.
3501 int Op = (SrcLane % 2) != Lane;
3502 LaneCrossing |= Op;
3503 if (LaneSrcs[Lane][Op] >= 0 && LaneSrcs[Lane][Op] != SrcLane)
3504 Op ^= 1;
3505 if (LaneSrcs[Lane][Op] >= 0 && LaneSrcs[Lane][Op] != SrcLane)
3506 return SDValue();
3507 LaneSrcs[Lane][Op] = SrcLane;
3508 InLaneMask[i] = Op * Size + Lane * LaneSize + M % LaneSize;
3509 }
3510
3511 if (!LaneCrossing)
3512 return SDValue();
3513
3514 // Swap the operands of the high lane if that makes both lanes use the same
3515 // in-lane mask, which more patterns (e.g. XVPICKEV) can match.
3516 SmallVector<int, 16> RepeatedMask;
3517 if (!isRepeatedShuffleMask(128, VT, InLaneMask, RepeatedMask)) {
3518 SmallVector<int, 32> SwappedMask(InLaneMask);
3519 for (int i = LaneSize; i < Size; ++i)
3520 if (SwappedMask[i] >= 0)
3521 SwappedMask[i] = (SwappedMask[i] + Size) % (2 * Size);
3522 if (isRepeatedShuffleMask(128, VT, SwappedMask, RepeatedMask)) {
3523 std::swap(LaneSrcs[1][0], LaneSrcs[1][1]);
3524 InLaneMask = SwappedMask;
3525 }
3526 }
3527
3528 // Move the input lanes of each operand into place.
3529 SDValue Ops[2];
3530 for (int Op = 0; Op < 2; ++Op) {
3531 SmallVector<int, 32> LaneMask(Size, -1);
3532 for (int Lane = 0; Lane < 2; ++Lane)
3533 if (LaneSrcs[Lane][Op] >= 0)
3534 for (int i = 0; i < LaneSize; ++i)
3535 LaneMask[Lane * LaneSize + i] = LaneSrcs[Lane][Op] * LaneSize + i;
3536 Ops[Op] = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
3537
3538 // Exit if we got back the shuffle we started with, to avoid infinite
3539 // recursion.
3540 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Ops[Op]))
3541 if (SVN->getMask() == Mask)
3542 return SDValue();
3543 }
3544 return DAG.getVectorShuffle(VT, DL, Ops[0], Ops[1], InLaneMask);
3545}
3546
3547/// Dispatching routine to lower various 256-bit LoongArch vector shuffles.
3548///
3549/// This routine breaks down the specific type of 256-bit shuffle and
3550/// dispatches to the lowering routines accordingly.
3552 SDValue V1, SDValue V2, SelectionDAG &DAG,
3554 assert((VT.SimpleTy == MVT::v32i8 || VT.SimpleTy == MVT::v16i16 ||
3555 VT.SimpleTy == MVT::v8i32 || VT.SimpleTy == MVT::v4i64 ||
3556 VT.SimpleTy == MVT::v8f32 || VT.SimpleTy == MVT::v4f64) &&
3557 "Vector type is unsupported for lasx!");
3558 assert(V1.getSimpleValueType() == V2.getSimpleValueType() &&
3559 "Two operands have different types!");
3560 assert(VT.getVectorNumElements() == Mask.size() &&
3561 "Unexpected mask size for shuffle!");
3562 assert(Mask.size() % 2 == 0 && "Expected even mask size.");
3563 assert(Mask.size() >= 4 && "Mask size is less than 4.");
3564
3565 APInt KnownUndef, KnownZero;
3566 computeZeroableShuffleElements(Mask, V1, V2, KnownUndef, KnownZero);
3567 APInt Zeroable = KnownUndef | KnownZero;
3568
3569 SDValue Result;
3570 // TODO: Add more comparison patterns.
3571 if (V2.isUndef()) {
3572 if ((Result =
3573 lowerVECTOR_SHUFFLE_XVREPLVEI(DL, Mask, VT, V1, DAG, Subtarget)))
3574 return Result;
3575 if ((Result = lowerVECTOR_SHUFFLE_XVSHUF4I(DL, Mask, VT, V1, V2, DAG,
3576 Subtarget)))
3577 return Result;
3578 if ((Result = lowerVECTOR_SHUFFLE_XVREPLVE0(DL, Mask, VT, V1, DAG)))
3579 return Result;
3580 // Try to widen vectors to gain more optimization opportunities.
3581 if (SDValue NewShuffle = widenShuffleMask(DL, Mask, VT, V1, V2, DAG))
3582 return NewShuffle;
3583 if ((Result =
3584 lowerVECTOR_SHUFFLE_XVPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3585 return Result;
3586 if ((Result = lowerVECTOR_SHUFFLE_XVPERM(DL, Mask, VT, V1, DAG, Subtarget)))
3587 return Result;
3588 if ((Result =
3589 lowerVECTOR_SHUFFLE_IsReverse(DL, Mask, VT, V1, DAG, Subtarget)))
3590 return Result;
3591
3592 // TODO: This comment may be enabled in the future to better match the
3593 // pattern for instruction selection.
3594 /* V2 = V1; */
3595 }
3596
3597 // It is recommended not to change the pattern comparison order for better
3598 // performance.
3599 if ((Result = lowerVECTOR_SHUFFLE_XVPACKEV(DL, Mask, VT, V1, V2, DAG)))
3600 return Result;
3601 if ((Result = lowerVECTOR_SHUFFLE_XVPACKOD(DL, Mask, VT, V1, V2, DAG)))
3602 return Result;
3603 if ((Result = lowerVECTOR_SHUFFLE_XVILVH(DL, Mask, VT, V1, V2, DAG)))
3604 return Result;
3605 if ((Result = lowerVECTOR_SHUFFLE_XVILVL(DL, Mask, VT, V1, V2, DAG)))
3606 return Result;
3607 if ((Result = lowerVECTOR_SHUFFLE_XVPICKEV(DL, Mask, VT, V1, V2, DAG)))
3608 return Result;
3609 if ((Result = lowerVECTOR_SHUFFLE_XVPICKOD(DL, Mask, VT, V1, V2, DAG)))
3610 return Result;
3611 if ((VT.SimpleTy == MVT::v4i64 || VT.SimpleTy == MVT::v4f64) &&
3612 (Result =
3613 lowerVECTOR_SHUFFLE_XVSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3614 return Result;
3615 if ((Result =
3616 lowerVECTOR_SHUFFLE_XVEXTRINS(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3617 return Result;
3618 if ((Result = lowerVECTOR_SHUFFLEAsShift(DL, Mask, VT, V1, V2, DAG, Subtarget,
3619 Zeroable)))
3620 return Result;
3621 if ((Result =
3622 lowerVECTOR_SHUFFLE_XVPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3623 return Result;
3624 if ((Result =
3625 lowerVECTOR_SHUFFLE_XVINSVE0(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3626 return Result;
3627 if ((Result = lowerVECTOR_SHUFFLEAsByteRotate(DL, Mask, VT, V1, V2, DAG,
3628 Subtarget)))
3629 return Result;
3630
3631 if ((Result =
3632 lowerVECTOR_SHUFFLE_XVPERMIQ(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3633 return Result;
3634
3635 // canonicalize non cross-lane shuffle vector
3636 SmallVector<int> NewMask(Mask);
3637 if (canonicalizeShuffleVectorByLane(DL, NewMask, VT, V1, V2, DAG, Subtarget))
3638 return lower256BitShuffle(DL, NewMask, VT, V1, V2, DAG, Subtarget);
3639
3640 // FIXME: Handling the remaining cases earlier can degrade performance
3641 // in some situations. Further analysis is required to enable more
3642 // effective optimizations.
3643 if ((Result = lowerVECTOR_SHUFFLEAsLanePermuteAndShuffle(DL, NewMask, VT, V1,
3644 V2, DAG)))
3645 return Result;
3646
3647 if (SDValue NewShuffle = widenShuffleMask(DL, NewMask, VT, V1, V2, DAG))
3648 return NewShuffle;
3649 if ((Result = lowerVECTOR_SHUFFLE_XVSHUF(DL, NewMask, VT, V1, V2, DAG)))
3650 return Result;
3651
3652 return SDValue();
3653}
3654
3655SDValue LoongArchTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
3656 SelectionDAG &DAG) const {
3657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3658 ArrayRef<int> OrigMask = SVOp->getMask();
3659 SDValue V1 = Op.getOperand(0);
3660 SDValue V2 = Op.getOperand(1);
3661 MVT VT = Op.getSimpleValueType();
3662 int NumElements = VT.getVectorNumElements();
3663 SDLoc DL(Op);
3664
3665 bool V1IsUndef = V1.isUndef();
3666 bool V2IsUndef = V2.isUndef();
3667 if (V1IsUndef && V2IsUndef)
3668 return DAG.getUNDEF(VT);
3669
3670 // When we create a shuffle node we put the UNDEF node to second operand,
3671 // but in some cases the first operand may be transformed to UNDEF.
3672 // In this case we should just commute the node.
3673 if (V1IsUndef)
3674 return DAG.getCommutedVectorShuffle(*SVOp);
3675
3676 // Check for non-undef masks pointing at an undef vector and make the masks
3677 // undef as well. This makes it easier to match the shuffle based solely on
3678 // the mask.
3679 if (V2IsUndef &&
3680 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
3681 SmallVector<int, 8> NewMask(OrigMask);
3682 for (int &M : NewMask)
3683 if (M >= NumElements)
3684 M = -1;
3685 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
3686 }
3687
3688 // Check for illegal shuffle mask element index values.
3689 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
3690 (void)MaskUpperLimit;
3691 assert(llvm::all_of(OrigMask,
3692 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
3693 "Out of bounds shuffle index");
3694
3695 // For each vector width, delegate to a specialized lowering routine.
3696 if (VT.is128BitVector())
3697 return lower128BitShuffle(DL, OrigMask, VT, V1, V2, DAG, Subtarget);
3698
3699 if (VT.is256BitVector())
3700 return lower256BitShuffle(DL, OrigMask, VT, V1, V2, DAG, Subtarget);
3701
3702 return SDValue();
3703}
3704
3705SDValue LoongArchTargetLowering::lowerFP_TO_FP16(SDValue Op,
3706 SelectionDAG &DAG) const {
3707 // Custom lower to ensure the libcall return is passed in an FPR on hard
3708 // float ABIs.
3709 SDLoc DL(Op);
3710 MakeLibCallOptions CallOptions;
3711 SDValue Op0 = Op.getOperand(0);
3712 SDValue Chain = SDValue();
3713 RTLIB::Libcall LC = RTLIB::getFPROUND(Op0.getValueType(), MVT::f16);
3714 SDValue Res;
3715 std::tie(Res, Chain) =
3716 makeLibCall(DAG, LC, MVT::f32, Op0, CallOptions, DL, Chain);
3717 if (Subtarget.is64Bit())
3718 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Res);
3719 return DAG.getBitcast(MVT::i32, Res);
3720}
3721
3722SDValue LoongArchTargetLowering::lowerFP16_TO_FP(SDValue Op,
3723 SelectionDAG &DAG) const {
3724 // Custom lower to ensure the libcall argument is passed in an FPR on hard
3725 // float ABIs.
3726 SDLoc DL(Op);
3727 MakeLibCallOptions CallOptions;
3728 SDValue Op0 = Op.getOperand(0);
3729 SDValue Chain = SDValue();
3730 SDValue Arg = Subtarget.is64Bit() ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64,
3731 DL, MVT::f32, Op0)
3732 : DAG.getBitcast(MVT::f32, Op0);
3733 SDValue Res;
3734 std::tie(Res, Chain) = makeLibCall(DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Arg,
3735 CallOptions, DL, Chain);
3736 return Res;
3737}
3738
3739SDValue LoongArchTargetLowering::lowerFP_TO_BF16(SDValue Op,
3740 SelectionDAG &DAG) const {
3741 assert(Subtarget.hasBasicF() && "Unexpected custom legalization");
3742 SDLoc DL(Op);
3743 MakeLibCallOptions CallOptions;
3744 RTLIB::Libcall LC =
3745 RTLIB::getFPROUND(Op.getOperand(0).getValueType(), MVT::bf16);
3746 SDValue Res =
3747 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
3748 if (Subtarget.is64Bit())
3749 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Res);
3750 return DAG.getBitcast(MVT::i32, Res);
3751}
3752
3753SDValue LoongArchTargetLowering::lowerBF16_TO_FP(SDValue Op,
3754 SelectionDAG &DAG) const {
3755 assert(Subtarget.hasBasicF() && "Unexpected custom legalization");
3756 MVT VT = Op.getSimpleValueType();
3757 SDLoc DL(Op);
3758 Op = DAG.getNode(
3759 ISD::SHL, DL, Op.getOperand(0).getValueType(), Op.getOperand(0),
3760 DAG.getShiftAmountConstant(16, Op.getOperand(0).getValueType(), DL));
3761 SDValue Res = Subtarget.is64Bit() ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64,
3762 DL, MVT::f32, Op)
3763 : DAG.getBitcast(MVT::f32, Op);
3764 if (VT != MVT::f32)
3765 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Res);
3766 return Res;
3767}
3768
3769// Lower BUILD_VECTOR as broadcast load (if possible).
3770// For example:
3771// %a = load i8, ptr %ptr
3772// %b = build_vector %a, %a, %a, %a
3773// is lowered to :
3774// (VLDREPL_B $a0, 0)
3776 const SDLoc &DL,
3777 SelectionDAG &DAG) {
3778 MVT VT = BVOp->getSimpleValueType(0);
3779 int NumOps = BVOp->getNumOperands();
3780
3781 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3782 "Unsupported vector type for broadcast.");
3783
3784 SDValue IdentitySrc;
3785 bool IsIdeneity = true;
3786
3787 for (int i = 0; i != NumOps; i++) {
3788 SDValue Op = BVOp->getOperand(i);
3789 if (Op.getOpcode() != ISD::LOAD || (IdentitySrc && Op != IdentitySrc)) {
3790 IsIdeneity = false;
3791 break;
3792 }
3793 IdentitySrc = BVOp->getOperand(0);
3794 }
3795
3796 // make sure that this load is valid and only has one user.
3797 if (!IsIdeneity || !IdentitySrc || !BVOp->isOnlyUserOf(IdentitySrc.getNode()))
3798 return SDValue();
3799
3800 auto *LN = cast<LoadSDNode>(IdentitySrc);
3801 auto ExtType = LN->getExtensionType();
3802
3803 if ((ExtType == ISD::EXTLOAD || ExtType == ISD::NON_EXTLOAD) &&
3804 VT.getScalarSizeInBits() == LN->getMemoryVT().getScalarSizeInBits()) {
3805 // Indexed loads and stores are not supported on LoongArch.
3806 assert(LN->isUnindexed() && "Unexpected indexed load.");
3807
3808 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3809 // The offset operand of unindexed load is always undefined, so there is
3810 // no need to pass it to VLDREPL.
3811 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
3812 SDValue BCast = DAG.getNode(LoongArchISD::VLDREPL, DL, Tys, Ops);
3813 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
3814 return BCast;
3815 }
3816 return SDValue();
3817}
3818
3819// Sequentially insert elements from Ops into Vector, from low to high indices.
3820// Note: Ops can have fewer elements than Vector.
3823 EVT ResTy) {
3824 assert(Ops.size() <= ResTy.getVectorNumElements());
3825
3826 SDValue Op0 = Ops[0];
3827 if (!Op0.isUndef())
3828 Vector = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ResTy, Op0);
3829 for (unsigned i = 1; i < Ops.size(); ++i) {
3830 SDValue Opi = Ops[i];
3831 if (Opi.isUndef())
3832 continue;
3833 Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Vector, Opi,
3834 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
3835 }
3836}
3837
3838// Build a ResTy subvector from Node, taking NumElts elements starting at index
3839// 'first'.
3841 SelectionDAG &DAG, SDLoc DL,
3843 EVT ResTy, unsigned first) {
3844 unsigned NumElts = ResTy.getVectorNumElements();
3845
3846 assert(first + NumElts <= Node->getSimpleValueType(0).getVectorNumElements());
3847
3848 SmallVector<SDValue, 16> Ops(Node->op_begin() + first,
3849 Node->op_begin() + first + NumElts);
3850 SDValue Vector = DAG.getUNDEF(ResTy);
3851 fillVector(Ops, DAG, DL, Subtarget, Vector, ResTy);
3852 return Vector;
3853}
3854
3855SDValue LoongArchTargetLowering::lowerBUILD_VECTOR(SDValue Op,
3856 SelectionDAG &DAG) const {
3857 BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);
3858 MVT VT = Node->getSimpleValueType(0);
3859 EVT ResTy = Op->getValueType(0);
3860 unsigned NumElts = ResTy.getVectorNumElements();
3861 SDLoc DL(Op);
3862 APInt SplatValue, SplatUndef;
3863 unsigned SplatBitSize;
3864 bool HasAnyUndefs;
3865 bool IsConstant = false;
3866 bool UseSameConstant = true;
3867 SDValue ConstantValue;
3868 bool Is128Vec = ResTy.is128BitVector();
3869 bool Is256Vec = ResTy.is256BitVector();
3870
3871 if ((!Subtarget.hasExtLSX() || !Is128Vec) &&
3872 (!Subtarget.hasExtLASX() || !Is256Vec))
3873 return SDValue();
3874
3875 if (SDValue Result = lowerBUILD_VECTORAsBroadCastLoad(Node, DL, DAG))
3876 return Result;
3877
3878 if (Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
3879 /*MinSplatBits=*/8) &&
3880 SplatBitSize <= 64) {
3881 // We can only cope with 8, 16, 32, or 64-bit elements.
3882 if (SplatBitSize != 8 && SplatBitSize != 16 && SplatBitSize != 32 &&
3883 SplatBitSize != 64)
3884 return SDValue();
3885
3886 if (SplatBitSize == 64 && !Subtarget.is64Bit()) {
3887 // We can only handle 64-bit elements that are within
3888 // the signed 10-bit range or match vldi patterns on 32-bit targets.
3889 // See the BUILD_VECTOR case in LoongArchDAGToDAGISel::Select().
3890 if (!SplatValue.isSignedIntN(10) &&
3891 !isImmVLDILegalForMode1(SplatValue, SplatBitSize).first)
3892 return SDValue();
3893 if ((Is128Vec && ResTy == MVT::v4i32) ||
3894 (Is256Vec && ResTy == MVT::v8i32))
3895 return Op;
3896 }
3897
3898 EVT ViaVecTy;
3899
3900 switch (SplatBitSize) {
3901 default:
3902 return SDValue();
3903 case 8:
3904 ViaVecTy = Is128Vec ? MVT::v16i8 : MVT::v32i8;
3905 break;
3906 case 16:
3907 ViaVecTy = Is128Vec ? MVT::v8i16 : MVT::v16i16;
3908 break;
3909 case 32:
3910 ViaVecTy = Is128Vec ? MVT::v4i32 : MVT::v8i32;
3911 break;
3912 case 64:
3913 ViaVecTy = Is128Vec ? MVT::v2i64 : MVT::v4i64;
3914 break;
3915 }
3916
3917 // SelectionDAG::getConstant will promote SplatValue appropriately.
3918 SDValue Result = DAG.getConstant(SplatValue, DL, ViaVecTy);
3919
3920 // Bitcast to the type we originally wanted.
3921 if (ViaVecTy != ResTy)
3922 Result = DAG.getNode(ISD::BITCAST, SDLoc(Node), ResTy, Result);
3923
3924 return Result;
3925 }
3926
3927 if (DAG.isSplatValue(Op, /*AllowUndefs=*/false))
3928 return Op;
3929
3930 for (unsigned i = 0; i < NumElts; ++i) {
3931 SDValue Opi = Node->getOperand(i);
3932 if (isIntOrFPConstant(Opi)) {
3933 IsConstant = true;
3934 if (!ConstantValue.getNode())
3935 ConstantValue = Opi;
3936 else if (ConstantValue != Opi)
3937 UseSameConstant = false;
3938 }
3939 }
3940
3941 // If the type of BUILD_VECTOR is v2f64, custom legalizing it has no benefits.
3942 if (IsConstant && UseSameConstant && ResTy != MVT::v2f64) {
3943 SDValue Result = DAG.getSplatBuildVector(ResTy, DL, ConstantValue);
3944 for (unsigned i = 0; i < NumElts; ++i) {
3945 SDValue Opi = Node->getOperand(i);
3946 if (!isIntOrFPConstant(Opi))
3947 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Result, Opi,
3948 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
3949 }
3950 return Result;
3951 }
3952
3953 if (!IsConstant) {
3955 BitVector UndefElements;
3956 bool IsRepeated = Node->getRepeatedSequence(Sequence, &UndefElements);
3957 unsigned SeqLen = Sequence.size();
3958 unsigned NumUndefElts = UndefElements.count();
3959
3960 // When a BUILD_VECTOR consists of the same element (ignoring undefs),
3961 // prefer emitting a broadcast instead of multiple insertions.
3962 if (IsRepeated && SeqLen == 1) {
3963 bool IsSplatBetter = true;
3964
3965 // Integer vectors benefit from splat except in the case where the only
3966 // non-undef element is at index 0 and is a load with a base+offset addr.
3967 if (ResTy.isInteger()) {
3968 SDValue Op0 = Node->getOperand(0);
3969 if (NumUndefElts == NumElts - 1 && Op0.getOpcode() == ISD::LOAD &&
3971 IsSplatBetter = false;
3972 }
3973
3974 // Several floating-point cases suffer performance regressions or have
3975 // no improvement when
3976 // only one element is non-undef,
3977 // one of the only two non-undefs at index 0,
3978 // the two non-undefs of v8f32 buildvector at index (1,2)/(1,3)/(2,3).
3979 if (ResTy.isFloatingPoint()) {
3980 if (NumUndefElts == NumElts - 1)
3981 IsSplatBetter = false;
3982 if (NumUndefElts == NumElts - 2 && !UndefElements[0])
3983 IsSplatBetter = false;
3984 if (ResTy == MVT::v8f32 && NumUndefElts == NumElts - 2 &&
3985 ((!UndefElements[1] && !UndefElements[2]) ||
3986 (!UndefElements[1] && !UndefElements[3]) ||
3987 (!UndefElements[2] && !UndefElements[3])))
3988 IsSplatBetter = false;
3989 }
3990
3991 if (IsSplatBetter)
3992 return DAG.getSplatBuildVector(ResTy, DL, Sequence[0]);
3993 }
3994
3995 // If the BUILD_VECTOR has a repeated pattern, use INSERT_VECTOR_ELT to fill
3996 // the sub-sequence of the vector and then broadcast the sub-sequence.
3997 //
3998 // TODO: If the BUILD_VECTOR contains undef elements, consider falling
3999 // back to use INSERT_VECTOR_ELT to materialize the vector, because it
4000 // generates worse code in some cases. This could be further optimized
4001 // with more consideration.
4002 if (IsRepeated && NumUndefElts == 0) {
4003 // Using LSX instructions to fill the sub-sequence of 256-bits vector,
4004 // because the high part can be simply treated as undef.
4005 SDValue Vector = DAG.getUNDEF(ResTy);
4006 EVT FillTy = Is256Vec
4008 : ResTy;
4009 SDValue FillVec =
4010 Is256Vec ? DAG.getExtractSubvector(DL, FillTy, Vector, 0) : Vector;
4011
4012 fillVector(Sequence, DAG, DL, Subtarget, FillVec, FillTy);
4013
4014 unsigned SplatLen = NumElts / SeqLen;
4015 MVT SplatEltTy = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
4016 MVT SplatTy = MVT::getVectorVT(SplatEltTy, SplatLen);
4017
4018 // If size of the sub-sequence is half of a 256-bits vector, bitcast the
4019 // vector to v4i64 type in order to match the pattern of XVREPLVE0Q.
4020 if (SplatEltTy == MVT::i128)
4021 SplatTy = MVT::v4i64;
4022
4023 SDValue SplatVec;
4024 SDValue SrcVec = DAG.getBitcast(
4025 SplatTy,
4026 Is256Vec ? DAG.getInsertSubvector(DL, Vector, FillVec, 0) : FillVec);
4027 if (Is256Vec) {
4028 SplatVec =
4029 DAG.getNode((SplatEltTy == MVT::i128) ? LoongArchISD::XVREPLVE0Q
4030 : LoongArchISD::XVREPLVE0,
4031 DL, SplatTy, SrcVec);
4032 } else {
4033 SplatVec = DAG.getNode(LoongArchISD::VREPLVEI, DL, SplatTy, SrcVec,
4034 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
4035 }
4036
4037 return DAG.getBitcast(ResTy, SplatVec);
4038 }
4039
4040 // Use INSERT_VECTOR_ELT operations rather than expand to stores, because
4041 // using memory operations is much lower.
4042 //
4043 // For 256-bit vectors, normally split into two halves and concatenate.
4044 // Special case: for v8i32/v8f32/v4i64/v4f64, if the upper half has only
4045 // one non-undef element, skip spliting to avoid a worse result.
4046 if (ResTy == MVT::v8i32 || ResTy == MVT::v8f32 || ResTy == MVT::v4i64 ||
4047 ResTy == MVT::v4f64) {
4048 unsigned NonUndefCount = 0;
4049 for (unsigned i = NumElts / 2; i < NumElts; ++i) {
4050 if (!Node->getOperand(i).isUndef()) {
4051 ++NonUndefCount;
4052 if (NonUndefCount > 1)
4053 break;
4054 }
4055 }
4056 if (NonUndefCount == 1)
4057 return fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget, ResTy, 0);
4058 }
4059
4060 EVT VecTy =
4061 Is256Vec ? ResTy.getHalfNumVectorElementsVT(*DAG.getContext()) : ResTy;
4062 SDValue Vector =
4063 fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget, VecTy, 0);
4064
4065 if (Is128Vec)
4066 return Vector;
4067
4068 SDValue VectorHi = fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget,
4069 VecTy, NumElts / 2);
4070
4071 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResTy, Vector, VectorHi);
4072 }
4073
4074 return SDValue();
4075}
4076
4077SDValue LoongArchTargetLowering::lowerCONCAT_VECTORS(SDValue Op,
4078 SelectionDAG &DAG) const {
4079 SDLoc DL(Op);
4080 MVT ResVT = Op.getSimpleValueType();
4081 assert(ResVT.is256BitVector() && Op.getNumOperands() == 2);
4082
4083 if (Op.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4084 Op.getOperand(1).getOpcode() == ISD::TRUNCATE)
4085 return Op;
4086
4087 unsigned NumOperands = Op.getNumOperands();
4088 unsigned NumFreezeUndef = 0;
4089 unsigned NumZero = 0;
4090 unsigned NumNonZero = 0;
4091 unsigned NonZeros = 0;
4092 SmallSet<SDValue, 4> Undefs;
4093 for (unsigned i = 0; i != NumOperands; ++i) {
4094 SDValue SubVec = Op.getOperand(i);
4095 if (SubVec.isUndef())
4096 continue;
4097 if (ISD::isFreezeUndef(SubVec)) {
4098 // If the freeze(undef) has multiple uses then we must fold to zero.
4099 if (SubVec.hasOneUse()) {
4100 ++NumFreezeUndef;
4101 } else {
4102 ++NumZero;
4103 Undefs.insert(SubVec);
4104 }
4105 } else if (ISD::isBuildVectorAllZeros(SubVec))
4106 ++NumZero;
4107 else {
4108 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
4109 NonZeros |= 1 << i;
4110 ++NumNonZero;
4111 }
4112 }
4113
4114 // If we have more than 2 non-zeros, build each half separately.
4115 if (NumNonZero > 2) {
4116 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
4117 ArrayRef<SDUse> Ops = Op->ops();
4118 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
4119 Ops.slice(0, NumOperands / 2));
4120 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
4121 Ops.slice(NumOperands / 2));
4122 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
4123 }
4124
4125 // Otherwise, build it up through insert_subvectors.
4126 SDValue Vec = NumZero ? DAG.getConstant(0, DL, ResVT)
4127 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
4128 : DAG.getUNDEF(ResVT));
4129
4130 // Replace Undef operands with ZeroVector.
4131 for (SDValue U : Undefs)
4132 DAG.ReplaceAllUsesWith(U, DAG.getConstant(0, DL, U.getSimpleValueType()));
4133
4134 MVT SubVT = Op.getOperand(0).getSimpleValueType();
4135 unsigned NumSubElems = SubVT.getVectorNumElements();
4136 for (unsigned i = 0; i != NumOperands; ++i) {
4137 if ((NonZeros & (1 << i)) == 0)
4138 continue;
4139
4140 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResVT, Vec, Op.getOperand(i),
4141 DAG.getVectorIdxConstant(i * NumSubElems, DL));
4142 }
4143
4144 return Vec;
4145}
4146
4147SDValue
4148LoongArchTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4149 SelectionDAG &DAG) const {
4150 MVT EltVT = Op.getSimpleValueType();
4151 SDValue Vec = Op->getOperand(0);
4152 EVT VecTy = Vec->getValueType(0);
4153 SDValue Idx = Op->getOperand(1);
4154 SDLoc DL(Op);
4155 MVT GRLenVT = Subtarget.getGRLenVT();
4156
4157 assert(VecTy.is256BitVector() && "Unexpected EXTRACT_VECTOR_ELT vector type");
4158
4159 if (isa<ConstantSDNode>(Idx))
4160 return Op;
4161
4162 switch (VecTy.getSimpleVT().SimpleTy) {
4163 default:
4164 llvm_unreachable("Unexpected type");
4165 case MVT::v32i8:
4166 case MVT::v16i16:
4167 case MVT::v4i64:
4168 case MVT::v4f64: {
4169 // Extract the high half subvector and place it to the low half of a new
4170 // vector. It doesn't matter what the high half of the new vector is.
4171 EVT HalfTy = VecTy.getHalfNumVectorElementsVT(*DAG.getContext());
4172 SDValue VecHi =
4173 DAG.getExtractSubvector(DL, HalfTy, Vec, HalfTy.getVectorNumElements());
4174 SDValue TmpVec =
4175 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecTy, DAG.getUNDEF(VecTy),
4176 VecHi, DAG.getConstant(0, DL, GRLenVT));
4177
4178 // Shuffle the origin Vec and the TmpVec using MaskVec, the lowest element
4179 // of MaskVec is Idx, the rest do not matter. ResVec[0] will hold the
4180 // desired element.
4181 SDValue IdxCp =
4182 Subtarget.is64Bit()
4183 ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, Idx)
4184 : DAG.getBitcast(MVT::f32, Idx);
4185 SDValue IdxVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f32, IdxCp);
4186 SDValue MaskVec =
4187 DAG.getBitcast((VecTy == MVT::v4f64) ? MVT::v4i64 : VecTy, IdxVec);
4188 SDValue ResVec =
4189 DAG.getNode(LoongArchISD::VSHUF, DL, VecTy, MaskVec, TmpVec, Vec);
4190
4191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ResVec,
4192 DAG.getConstant(0, DL, GRLenVT));
4193 }
4194 case MVT::v8i32:
4195 case MVT::v8f32: {
4196 SDValue SplatIdx = DAG.getSplatBuildVector(MVT::v8i32, DL, Idx);
4197 SDValue SplatValue =
4198 DAG.getNode(LoongArchISD::XVPERM, DL, VecTy, Vec, SplatIdx);
4199
4200 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, SplatValue,
4201 DAG.getConstant(0, DL, GRLenVT));
4202 }
4203 }
4204}
4205
4206SDValue
4207LoongArchTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4208 SelectionDAG &DAG) const {
4209 MVT VT = Op.getSimpleValueType();
4210 MVT EltVT = VT.getVectorElementType();
4211 unsigned NumElts = VT.getVectorNumElements();
4212 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
4213 SDLoc DL(Op);
4214 SDValue Op0 = Op.getOperand(0);
4215 SDValue Op1 = Op.getOperand(1);
4216 SDValue Op2 = Op.getOperand(2);
4217
4218 // Lower inserting a loaded integer into lane 0 of an undefined vector as a
4219 // vector load that writes the whole register: FLD.{S/D} for 32/64-bit
4220 // elements and [X]VLDREPL.{B/H} for 8/16-bit ones. Unlike a scalar load +
4221 // [X]VINSGR2VR, it has no false dependency on the previous value of the
4222 // destination and doesn't need to move the value from a GPR.
4223 // For example:
4224 // %a = load i64, ptr %ptr
4225 // %b = insert_vector_elt undef, %a, 0
4226 // is lowered to:
4227 // (FLD_D $a0, 0)
4228 if (Op0.isUndef() && isNullConstant(Op2) && EltVT.isInteger() &&
4229 Op1.getOpcode() == ISD::LOAD && Op1.hasOneUse()) {
4230 auto *LN = cast<LoadSDNode>(Op1);
4231 auto ExtType = LN->getExtensionType();
4232 if (LN->isSimple() &&
4233 (ExtType == ISD::EXTLOAD || ExtType == ISD::NON_EXTLOAD) &&
4234 LN->getMemoryVT().getSizeInBits() == EltSizeInBits) {
4235 // Indexed loads and stores are not supported on LoongArch.
4236 assert(LN->isUnindexed() && "Unexpected indexed load.");
4237 SDValue Res;
4238 if (EltSizeInBits >= 32) {
4239 MVT FltVT = MVT::getFloatingPointVT(EltSizeInBits);
4240 // Don't reuse the memory operand, its range metadata (if any) only
4241 // applies to integer loads.
4242 SDValue Ld = DAG.getLoad(
4243 FltVT, DL, LN->getChain(), LN->getBasePtr(), LN->getPointerInfo(),
4244 LN->getAlign(), LN->getMemOperand()->getFlags(), LN->getAAInfo());
4245 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL,
4246 MVT::getVectorVT(FltVT, NumElts), Ld);
4247 Res = DAG.getBitcast(VT, Res);
4248 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), Ld.getValue(1));
4249 } else {
4250 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
4251 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
4252 Res = DAG.getMemIntrinsicNode(LoongArchISD::VLDREPL, DL, Tys, Ops,
4253 LN->getMemoryVT(), LN->getMemOperand());
4254 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), Res.getValue(1));
4255 }
4256 return Res;
4257 }
4258 }
4259
4260 if (isa<ConstantSDNode>(Op2))
4261 return Op;
4262
4263 MVT IdxTy = MVT::getIntegerVT(EltSizeInBits);
4264 MVT IdxVTy = MVT::getVectorVT(IdxTy, NumElts);
4265
4266 if (!isTypeLegal(VT) || !isTypeLegal(IdxVTy))
4267 return SDValue();
4268
4269 SDValue SplatElt = DAG.getSplatBuildVector(VT, DL, Op1);
4270 SmallVector<SDValue, 32> RawIndices;
4271 SDValue SplatIdx;
4272 SDValue Indices;
4273
4274 if (!Subtarget.is64Bit() && IdxTy == MVT::i64) {
4275 MVT PairVTy = MVT::getVectorVT(MVT::i32, NumElts * 2);
4276 for (unsigned i = 0; i < NumElts; ++i) {
4277 RawIndices.push_back(Op2);
4278 RawIndices.push_back(DAG.getConstant(0, DL, MVT::i32));
4279 }
4280 SplatIdx = DAG.getBuildVector(PairVTy, DL, RawIndices);
4281 SplatIdx = DAG.getBitcast(IdxVTy, SplatIdx);
4282
4283 RawIndices.clear();
4284 for (unsigned i = 0; i < NumElts; ++i) {
4285 RawIndices.push_back(DAG.getConstant(i, DL, MVT::i32));
4286 RawIndices.push_back(DAG.getConstant(0, DL, MVT::i32));
4287 }
4288 Indices = DAG.getBuildVector(PairVTy, DL, RawIndices);
4289 Indices = DAG.getBitcast(IdxVTy, Indices);
4290 } else {
4291 SplatIdx = DAG.getSplatBuildVector(IdxVTy, DL, Op2);
4292
4293 for (unsigned i = 0; i < NumElts; ++i)
4294 RawIndices.push_back(DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
4295 Indices = DAG.getBuildVector(IdxVTy, DL, RawIndices);
4296 }
4297
4298 // insert vec, elt, idx
4299 // =>
4300 // select (splatidx == {0,1,2...}) ? splatelt : vec
4301 SDValue SelectCC =
4302 DAG.getSetCC(DL, IdxVTy, SplatIdx, Indices, ISD::CondCode::SETEQ);
4303 return DAG.getNode(ISD::VSELECT, DL, VT, SelectCC, SplatElt, Op0);
4304}
4305
4306SDValue LoongArchTargetLowering::lowerATOMIC_FENCE(SDValue Op,
4307 SelectionDAG &DAG) const {
4308 SDLoc DL(Op);
4309 SyncScope::ID FenceSSID =
4310 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4311
4312 // singlethread fences only synchronize with signal handlers on the same
4313 // thread and thus only need to preserve instruction order, not actually
4314 // enforce memory ordering.
4315 if (FenceSSID == SyncScope::SingleThread)
4316 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
4317 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
4318
4319 return Op;
4320}
4321
4323 MVT GRLenVT, SDValue RMValue) {
4324 // LLVM rounding mode encoding differs from LoongArch FCSR encoding:
4325 // LLVM: 0=RTZ, 1=RNE, 2=RUP, 3=RDN
4326 // FCSR: 0=RNE, 1=RZ, 2=RP, 3=RN
4327 //
4328 // The conversion swaps encodings 0 and 1 while preserving 2 and 3.
4329 // Since the transformation is self-inverse, it applies in both directions:
4330 // LLVM RM <-> LoongArch FCSR RM
4331 //
4332 // Transformation: RM ^ (~(RM >> 1) & 1)
4333 SDValue ShiftRight1 = DAG.getNode(ISD::SRL, DL, GRLenVT, RMValue,
4334 DAG.getConstant(1, DL, GRLenVT));
4335
4336 SDValue SwapMask = DAG.getNode(ISD::AND, DL, GRLenVT,
4337 DAG.getNode(ISD::XOR, DL, GRLenVT, ShiftRight1,
4338 DAG.getConstant(1, DL, GRLenVT)),
4339 DAG.getConstant(1, DL, GRLenVT));
4340
4341 return DAG.getNode(ISD::XOR, DL, GRLenVT, RMValue, SwapMask);
4342}
4343
4344SDValue LoongArchTargetLowering::lowerSET_ROUNDING(SDValue Op,
4345 SelectionDAG &DAG) const {
4346 MVT GRLenVT = Subtarget.getGRLenVT();
4347 SDLoc DL(Op);
4348 SDValue Chain = Op.getOperand(0);
4349 SDValue RMValue = Op.getOperand(1);
4350
4351 if (auto *CVal = dyn_cast<ConstantSDNode>(RMValue)) {
4352 uint64_t RM = CVal->getZExtValue();
4353 if (RM > 3) {
4355 LLVMContext &C = MF.getFunction().getContext();
4356 C.diagnose(DiagnosticInfoUnsupported(
4357 MF.getFunction(),
4358 "rounding mode is not supported by LoongArch hardware",
4359 DiagnosticLocation(DL.getDebugLoc()), DS_Error));
4360 return Chain;
4361 }
4362 }
4363
4364 RMValue = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, RMValue);
4365 RMValue = convertRMEncoding(DAG, DL, GRLenVT, RMValue);
4366
4367 // The RM field in FCSR is at bits [9:8]. Shift the rounding mode value
4368 // into position before writing via WRFCSR.
4369 RMValue = DAG.getNode(ISD::SHL, DL, GRLenVT, RMValue,
4370 DAG.getConstant(8, DL, GRLenVT));
4371
4372 // FCSR3 is an alias of the RM field; writing it avoids clobbering
4373 // unrelated fields in FCSR0.
4374 SDValue FCSRNo = DAG.getTargetConstant(3, DL, GRLenVT);
4375 MachineSDNode *RN = DAG.getMachineNode(LoongArch::WRFCSR, DL, MVT::Other,
4376 FCSRNo, RMValue, Chain);
4377 return SDValue(RN, 0);
4378}
4379
4380SDValue LoongArchTargetLowering::lowerGET_ROUNDING(SDValue Op,
4381 SelectionDAG &DAG) const {
4382 MVT GRLenVT = Subtarget.getGRLenVT();
4383 SDLoc DL(Op);
4384 SDValue Chain = Op->getOperand(0);
4385
4386 // FCSR3 is an alias of the RM field.
4387 SDValue FCSRNo = DAG.getTargetConstant(3, DL, GRLenVT);
4388 MachineSDNode *FCSR = DAG.getMachineNode(LoongArch::RDFCSR, DL, GRLenVT,
4389 MVT::Other, FCSRNo, Chain);
4390 SDValue RMValue = SDValue(FCSR, 0);
4391 Chain = SDValue(FCSR, 1);
4392
4393 // The RM field in FCSR is at bits [9:8].
4394 RMValue = DAG.getNode(ISD::SRL, DL, GRLenVT, RMValue,
4395 DAG.getConstant(8, DL, GRLenVT));
4396 RMValue = convertRMEncoding(DAG, DL, GRLenVT, RMValue);
4397
4398 SDValue RetVal = DAG.getZExtOrTrunc(RMValue, DL, Op.getValueType());
4399 return DAG.getMergeValues({RetVal, Chain}, DL);
4400}
4401
4402SDValue LoongArchTargetLowering::lowerWRITE_REGISTER(SDValue Op,
4403 SelectionDAG &DAG) const {
4404
4405 if (Subtarget.is64Bit() && Op.getOperand(2).getValueType() == MVT::i32) {
4406 DAG.getContext()->emitError(
4407 "On LA64, only 64-bit registers can be written.");
4408 return Op.getOperand(0);
4409 }
4410
4411 if (!Subtarget.is64Bit() && Op.getOperand(2).getValueType() == MVT::i64) {
4412 DAG.getContext()->emitError(
4413 "On LA32, only 32-bit registers can be written.");
4414 return Op.getOperand(0);
4415 }
4416
4417 return Op;
4418}
4419
4420SDValue LoongArchTargetLowering::lowerFRAMEADDR(SDValue Op,
4421 SelectionDAG &DAG) const {
4422 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
4423 DAG.getContext()->emitError("argument to '__builtin_frame_address' must "
4424 "be a constant integer");
4425 return SDValue();
4426 }
4427
4430 Register FrameReg = Subtarget.getRegisterInfo()->getFrameRegister(MF);
4431 EVT VT = Op.getValueType();
4432 SDLoc DL(Op);
4433 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4434 unsigned Depth = Op.getConstantOperandVal(0);
4435 int GRLenInBytes = Subtarget.getGRLen() / 8;
4436
4437 while (Depth--) {
4438 int Offset = -(GRLenInBytes * 2);
4439 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4440 DAG.getSignedConstant(Offset, DL, VT));
4441 FrameAddr =
4442 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4443 }
4444 return FrameAddr;
4445}
4446
4447SDValue LoongArchTargetLowering::lowerRETURNADDR(SDValue Op,
4448 SelectionDAG &DAG) const {
4449 // Currently only support lowering return address for current frame.
4450 if (Op.getConstantOperandVal(0) != 0) {
4451 DAG.getContext()->emitError(
4452 "return address can only be determined for the current frame");
4453 return SDValue();
4454 }
4455
4458 MVT GRLenVT = Subtarget.getGRLenVT();
4459
4460 // Return the value of the return address register, marking it an implicit
4461 // live-in.
4462 Register Reg = MF.addLiveIn(Subtarget.getRegisterInfo()->getRARegister(),
4463 getRegClassFor(GRLenVT));
4464 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, GRLenVT);
4465}
4466
4467SDValue LoongArchTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
4468 SelectionDAG &DAG) const {
4470 auto Size = Subtarget.getGRLen() / 8;
4471 auto FI = MF.getFrameInfo().CreateFixedObject(Size, 0, false);
4472 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4473}
4474
4475SDValue LoongArchTargetLowering::lowerVASTART(SDValue Op,
4476 SelectionDAG &DAG) const {
4478 auto *FuncInfo = MF.getInfo<LoongArchMachineFunctionInfo>();
4479
4480 SDLoc DL(Op);
4481 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4483
4484 // vastart just stores the address of the VarArgsFrameIndex slot into the
4485 // memory location argument.
4486 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4487 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4488 MachinePointerInfo(SV));
4489}
4490
4491// Lower an unsigned vXi64 -> vXf32 conversion to the same round-to-odd
4492// sequence that the generic legalizer uses for the scalar case:
4493//
4494// Odd = (x >> 1) | (x & 1)
4495// Doubled = (float)(int64_t)Odd + (float)(int64_t)Odd // exact, no rounding
4496// Signed = (float)(int64_t)x // valid for x < 2^63
4497// Result = x < 0 ? Doubled : Signed
4498//
4499// The generic half-word expansion is not usable here: it converts the high and
4500// low 32-bit halves separately and adds them, rounding three times, which is
4501// not enough to emulate the single rounding required by uitofp.
4502SDValue LoongArchTargetLowering::lowerUINT_TO_FPToF32(SDValue Op,
4503 SelectionDAG &DAG) const {
4504 SDLoc DL(Op);
4505 SDValue Src = Op.getOperand(0);
4506 EVT SrcVT = Src.getValueType();
4507 EVT DstVT = Op.getValueType();
4508
4509 SDValue Shift = DAG.getShiftAmountConstant(1, SrcVT, DL);
4510 SDValue Half = DAG.getNode(ISD::SRL, DL, SrcVT, Src, Shift);
4511 SDValue Sticky =
4512 DAG.getNode(ISD::AND, DL, SrcVT, Src, DAG.getConstant(1, DL, SrcVT));
4513 SDValue Odd = DAG.getNode(ISD::OR, DL, SrcVT, Half, Sticky);
4514
4515 // Doubling a value with at most 24 significant bits is exact.
4516 SDValue RoundToOdd = DAG.getNode(ISD::SINT_TO_FP, DL, DstVT, Odd);
4517 SDValue Doubled = DAG.getNode(ISD::FADD, DL, DstVT, RoundToOdd, RoundToOdd);
4518
4519 // Values below 2^63 convert directly; above that the signed conversion is
4520 // negative, so the round-to-odd path is used instead.
4521 SDValue Signed = DAG.getNode(ISD::SINT_TO_FP, DL, DstVT, Src);
4522
4523 // The signed conversion is negative exactly when the source did not fit, so
4524 // its sign bit is the mask: broadcasting it with an arithmetic shift avoids
4525 // a comparison followed by a truncate of the 64-bit result to the width of
4526 // the result vector.
4527 EVT MaskVT = DstVT.changeVectorElementTypeToInteger();
4528 SDValue Mask =
4529 DAG.getNode(ISD::SRA, DL, MaskVT, DAG.getBitcast(MaskVT, Signed),
4530 DAG.getShiftAmountConstant(31, MaskVT, DL));
4531 return DAG.getSelect(DL, DstVT, Mask, Doubled, Signed);
4532}
4533
4534SDValue LoongArchTargetLowering::lowerUINT_TO_FP(SDValue Op,
4535 SelectionDAG &DAG) const {
4536 SDLoc DL(Op);
4537 SDValue Op0 = Op.getOperand(0);
4538 EVT VT = Op.getValueType();
4539 EVT Op0VT = Op0.getValueType();
4540
4541 if (VT.isVector()) {
4542 if (VT.getScalarSizeInBits() == Op0VT.getScalarSizeInBits())
4543 return Op;
4544
4545 // There is no unsigned 64-bit to 32-bit conversion instruction, so
4546 // synthesize one with a single rounding. A value known to be
4547 // non-negative converts exactly as signed, and that form is native.
4548 if (Subtarget.hasExtLASX() && Op0VT.getScalarType() == MVT::i64 &&
4549 VT.getScalarType() == MVT::f32) {
4550 if (DAG.SignBitIsZero(Op0) || Op->getFlags().hasNonNeg())
4551 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, Op0);
4552 return lowerUINT_TO_FPToF32(Op, DAG);
4553 }
4554
4555 return SDValue();
4556 }
4557
4558 if ((DAG.SignBitIsZero(Op0) || Op->getFlags().hasNonNeg()) &&
4561 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, Op0);
4562
4563 // We can't do uint64 -> double -> float because of double-rounding issue.
4564 if (Subtarget.hasExtLSX() && Op0VT == MVT::i64 && VT == MVT::f64) {
4565 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i64, Op0);
4566 SDValue Conv = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::v2f64, Op0);
4567 Conv = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64, Conv,
4568 DAG.getIntPtrConstant(0, DL));
4569 return Conv;
4570 }
4571
4572 if (!Subtarget.is64Bit() || !Subtarget.hasBasicF() || Subtarget.hasBasicD())
4573 return SDValue();
4574
4575 assert(Subtarget.is64Bit() && Subtarget.hasBasicF() &&
4576 !Subtarget.hasBasicD() && "unexpected target features");
4577
4578 if (Op0->getOpcode() == ISD::AND) {
4579 auto *C = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4580 if (C && C->getZExtValue() < UINT64_C(0xFFFFFFFF))
4581 return Op;
4582 }
4583
4584 if (Op0->getOpcode() == LoongArchISD::BSTRPICK &&
4585 Op0.getConstantOperandVal(1) < UINT64_C(0X1F) &&
4586 Op0.getConstantOperandVal(2) == UINT64_C(0))
4587 return Op;
4588
4589 if (Op0.getOpcode() == ISD::AssertZext &&
4590 dyn_cast<VTSDNode>(Op0.getOperand(1))->getVT().bitsLT(MVT::i32))
4591 return Op;
4592
4593 EVT OpVT = Op0.getValueType();
4594 EVT RetVT = Op.getValueType();
4595 RTLIB::Libcall LC = RTLIB::getUINTTOFP(OpVT, RetVT);
4596 MakeLibCallOptions CallOptions;
4597 CallOptions.setTypeListBeforeSoften(OpVT, RetVT);
4598 SDValue Chain = SDValue();
4600 std::tie(Result, Chain) =
4601 makeLibCall(DAG, LC, Op.getValueType(), Op0, CallOptions, DL, Chain);
4602 return Result;
4603}
4604
4605SDValue LoongArchTargetLowering::lowerSINT_TO_FP(SDValue Op,
4606 SelectionDAG &DAG) const {
4607 assert(Subtarget.is64Bit() && Subtarget.hasBasicF() &&
4608 !Subtarget.hasBasicD() && "unexpected target features");
4609
4610 SDLoc DL(Op);
4611 SDValue Op0 = Op.getOperand(0);
4612
4613 if ((Op0.getOpcode() == ISD::AssertSext ||
4615 dyn_cast<VTSDNode>(Op0.getOperand(1))->getVT().bitsLE(MVT::i32))
4616 return Op;
4617
4618 EVT OpVT = Op0.getValueType();
4619 EVT RetVT = Op.getValueType();
4620 RTLIB::Libcall LC = RTLIB::getSINTTOFP(OpVT, RetVT);
4621 MakeLibCallOptions CallOptions;
4622 CallOptions.setTypeListBeforeSoften(OpVT, RetVT);
4623 SDValue Chain = SDValue();
4625 std::tie(Result, Chain) =
4626 makeLibCall(DAG, LC, Op.getValueType(), Op0, CallOptions, DL, Chain);
4627 return Result;
4628}
4629
4630SDValue LoongArchTargetLowering::lowerBITCAST(SDValue Op,
4631 SelectionDAG &DAG) const {
4632
4633 SDLoc DL(Op);
4634 EVT VT = Op.getValueType();
4635 SDValue Op0 = Op.getOperand(0);
4636 EVT Op0VT = Op0.getValueType();
4637
4638 if (Op.getValueType() == MVT::f32 && Op0VT == MVT::i32 &&
4639 Subtarget.is64Bit() && Subtarget.hasBasicF()) {
4640 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4641 return DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, NewOp0);
4642 }
4643 if (VT == MVT::f64 && Op0VT == MVT::i64 && !Subtarget.is64Bit()) {
4644 SDValue Lo, Hi;
4645 std::tie(Lo, Hi) = DAG.SplitScalar(Op0, DL, MVT::i32, MVT::i32);
4646 return DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64, Lo, Hi);
4647 }
4648 return Op;
4649}
4650
4651SDValue LoongArchTargetLowering::lowerFP_TO_SINT(SDValue Op,
4652 SelectionDAG &DAG) const {
4653
4654 SDLoc DL(Op);
4655 SDValue Op0 = Op.getOperand(0);
4656
4657 if (Op0.getValueType() == MVT::f16)
4658 Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0);
4659
4660 if (Op.getValueSizeInBits() > 32 && Subtarget.hasBasicF() &&
4661 !Subtarget.hasBasicD()) {
4662 SDValue Dst = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f32, Op0);
4663 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Dst);
4664 }
4665
4666 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
4667 SDValue Trunc = DAG.getNode(LoongArchISD::FTINT, DL, FPTy, Op0);
4668 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Trunc);
4669}
4670
4671// [X]VFTINTRZ and FTINTRZ saturate out-of-range values and convert NaN to 0,
4672// which is exactly the semantics of FP_TO_SINT_SAT with a native saturation
4673// width.
4674SDValue LoongArchTargetLowering::lowerFP_TO_SINT_SAT(SDValue Op,
4675 SelectionDAG &DAG) const {
4676 SDLoc DL(Op);
4677 SDValue Src = Op.getOperand(0);
4678 EVT VT = Op.getValueType();
4679 EVT SrcVT = Src.getValueType();
4680 unsigned SatWidth = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4681
4682 // Vectors are selected by patterns.
4683 if (VT.isVector()) {
4684 if (SatWidth == VT.getScalarSizeInBits() &&
4685 SatWidth == SrcVT.getScalarSizeInBits())
4686 return Op;
4687 return SDValue();
4688 }
4689
4690 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
4691 return SDValue();
4692
4693 if (SatWidth == 32) {
4694 SDValue Ftint = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f32, Src);
4695 if (Subtarget.is64Bit())
4696 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, VT, Ftint);
4697 return DAG.getBitcast(VT, Ftint);
4698 }
4699
4700 if (SatWidth == 64 && Subtarget.is64Bit() && Subtarget.hasBasicD()) {
4701 SDValue Ftint = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f64, Src);
4702 return DAG.getBitcast(VT, Ftint);
4703 }
4704
4705 return SDValue();
4706}
4707
4708SDValue LoongArchTargetLowering::lowerFP_TO_UINT(SDValue Op,
4709 SelectionDAG &DAG) const {
4710 if (!Subtarget.hasExtLSX())
4711 return SDValue();
4712
4713 SDLoc DL(Op);
4714 SDValue Src = Op.getOperand(0);
4715 EVT VT = Op.getValueType();
4716 EVT SrcVT = Src.getValueType();
4717
4718 if (VT != MVT::i64)
4719 return SDValue();
4720
4721 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
4722 return SDValue();
4723
4724 if (SrcVT == MVT::f32)
4725 Src = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Src);
4726 Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, Src);
4727 SDValue Conv = DAG.getNode(ISD::FP_TO_UINT, DL, MVT::v2i64, Src);
4728 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Conv,
4729 DAG.getIntPtrConstant(0, DL));
4730}
4731
4733 SelectionDAG &DAG, unsigned Flags) {
4734 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
4735}
4736
4738 SelectionDAG &DAG, unsigned Flags) {
4739 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
4740 Flags);
4741}
4742
4744 SelectionDAG &DAG, unsigned Flags) {
4745 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
4746 N->getOffset(), Flags);
4747}
4748
4750 SelectionDAG &DAG, unsigned Flags) {
4751 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
4752}
4753
4754template <class NodeTy>
4755SDValue LoongArchTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4757 bool IsLocal) const {
4758 SDLoc DL(N);
4759 EVT Ty = getPointerTy(DAG.getDataLayout());
4760 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
4761 SDValue Load;
4762
4763 switch (M) {
4764 default:
4765 report_fatal_error("Unsupported code model");
4766
4767 case CodeModel::Large: {
4768 assert(Subtarget.is64Bit() && "Large code model requires LA64");
4769
4770 // This is not actually used, but is necessary for successfully matching
4771 // the PseudoLA_*_LARGE nodes.
4772 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4773 if (IsLocal) {
4774 // This generates the pattern (PseudoLA_PCREL_LARGE tmp sym), that
4775 // eventually becomes the desired 5-insn code sequence.
4776 Load = SDValue(DAG.getMachineNode(LoongArch::PseudoLA_PCREL_LARGE, DL, Ty,
4777 Tmp, Addr),
4778 0);
4779 } else {
4780 // This generates the pattern (PseudoLA_GOT_LARGE tmp sym), that
4781 // eventually becomes the desired 5-insn code sequence.
4782 Load = SDValue(
4783 DAG.getMachineNode(LoongArch::PseudoLA_GOT_LARGE, DL, Ty, Tmp, Addr),
4784 0);
4785 }
4786 break;
4787 }
4788
4789 case CodeModel::Small:
4790 case CodeModel::Medium:
4791 if (IsLocal) {
4792 // This generates the pattern (PseudoLA_PCREL sym), which
4793 //
4794 // for la32r expands to:
4795 // (addi.w (pcaddu12i %pcadd_hi20(sym)) %pcadd_lo12(.Lpcadd_hi)).
4796 //
4797 // for la32s and la64 expands to:
4798 // (addi.w/d (pcalau12i %pc_hi20(sym)) %pc_lo12(sym)).
4799 Load = SDValue(
4800 DAG.getMachineNode(LoongArch::PseudoLA_PCREL, DL, Ty, Addr), 0);
4801 } else {
4802 // This generates the pattern (PseudoLA_GOT sym), which
4803 //
4804 // for la32r expands to:
4805 // (ld.w (pcaddu12i %got_pcadd_hi20(sym)) %pcadd_lo12(.Lpcadd_hi)).
4806 //
4807 // for la32s and la64 expands to:
4808 // (ld.w/d (pcalau12i %got_pc_hi20(sym)) %got_pc_lo12(sym)).
4809 Load =
4810 SDValue(DAG.getMachineNode(LoongArch::PseudoLA_GOT, DL, Ty, Addr), 0);
4811 }
4812 }
4813
4814 if (!IsLocal) {
4815 // Mark the load instruction as invariant to enable hoisting in MachineLICM.
4817 MachineMemOperand *MemOp = MF.getMachineMemOperand(
4821 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
4822 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
4823 }
4824
4825 return Load;
4826}
4827
4828SDValue LoongArchTargetLowering::lowerBlockAddress(SDValue Op,
4829 SelectionDAG &DAG) const {
4830 return getAddr(cast<BlockAddressSDNode>(Op), DAG,
4831 DAG.getTarget().getCodeModel());
4832}
4833
4834SDValue LoongArchTargetLowering::lowerJumpTable(SDValue Op,
4835 SelectionDAG &DAG) const {
4836 return getAddr(cast<JumpTableSDNode>(Op), DAG,
4837 DAG.getTarget().getCodeModel());
4838}
4839
4840SDValue LoongArchTargetLowering::lowerConstantPool(SDValue Op,
4841 SelectionDAG &DAG) const {
4842 return getAddr(cast<ConstantPoolSDNode>(Op), DAG,
4843 DAG.getTarget().getCodeModel());
4844}
4845
4846SDValue LoongArchTargetLowering::lowerGlobalAddress(SDValue Op,
4847 SelectionDAG &DAG) const {
4848 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
4849 assert(N->getOffset() == 0 && "unexpected offset in global node");
4850 auto CM = DAG.getTarget().getCodeModel();
4851 const GlobalValue *GV = N->getGlobal();
4852
4853 if (GV->isDSOLocal() && isa<GlobalVariable>(GV)) {
4854 if (auto GCM = dyn_cast<GlobalVariable>(GV)->getCodeModel())
4855 CM = *GCM;
4856 }
4857
4858 return getAddr(N, DAG, CM, GV->isDSOLocal());
4859}
4860
4861SDValue LoongArchTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
4862 SelectionDAG &DAG,
4863 unsigned Opc, bool UseGOT,
4864 bool Large) const {
4865 SDLoc DL(N);
4866 EVT Ty = getPointerTy(DAG.getDataLayout());
4867 MVT GRLenVT = Subtarget.getGRLenVT();
4868
4869 // This is not actually used, but is necessary for successfully matching the
4870 // PseudoLA_*_LARGE nodes.
4871 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4872 SDValue Addr = DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, 0);
4873
4874 // Only IE needs an extra argument for large code model.
4875 SDValue Offset = Opc == LoongArch::PseudoLA_TLS_IE_LARGE
4876 ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
4877 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
4878
4879 // If it is LE for normal/medium code model, the add tp operation will occur
4880 // during the pseudo-instruction expansion.
4881 if (Opc == LoongArch::PseudoLA_TLS_LE && !Large)
4882 return Offset;
4883
4884 if (UseGOT) {
4885 // Mark the load instruction as invariant to enable hoisting in MachineLICM.
4887 MachineMemOperand *MemOp = MF.getMachineMemOperand(
4891 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
4892 DAG.setNodeMemRefs(cast<MachineSDNode>(Offset.getNode()), {MemOp});
4893 }
4894
4895 // Add the thread pointer.
4896 return DAG.getNode(ISD::ADD, DL, Ty, Offset,
4897 DAG.getRegister(LoongArch::R2, GRLenVT));
4898}
4899
4900SDValue LoongArchTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
4901 SelectionDAG &DAG,
4902 unsigned Opc,
4903 bool Large) const {
4904 SDLoc DL(N);
4905 EVT Ty = getPointerTy(DAG.getDataLayout());
4906 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
4907
4908 // This is not actually used, but is necessary for successfully matching the
4909 // PseudoLA_*_LARGE nodes.
4910 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4911
4912 // Use a PC-relative addressing mode to access the dynamic GOT address.
4913 SDValue Addr = DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, 0);
4914 SDValue Load = Large ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
4915 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
4916
4917 // Prepare argument list to generate call.
4919 Args.emplace_back(Load, CallTy);
4920
4921 // Setup call to __tls_get_addr.
4922 TargetLowering::CallLoweringInfo CLI(DAG);
4923 CLI.setDebugLoc(DL)
4924 .setChain(DAG.getEntryNode())
4925 .setLibCallee(CallingConv::C, CallTy,
4926 DAG.getExternalSymbol("__tls_get_addr", Ty),
4927 std::move(Args));
4928
4929 return LowerCallTo(CLI).first;
4930}
4931
4932SDValue LoongArchTargetLowering::getTLSDescAddr(GlobalAddressSDNode *N,
4933 SelectionDAG &DAG, unsigned Opc,
4934 bool Large) const {
4935 SDLoc DL(N);
4936 EVT Ty = getPointerTy(DAG.getDataLayout());
4937 const GlobalValue *GV = N->getGlobal();
4938
4939 // This is not actually used, but is necessary for successfully matching the
4940 // PseudoLA_*_LARGE nodes.
4941 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4942
4943 // Use a PC-relative addressing mode to access the global dynamic GOT address.
4944 // This generates the pattern (PseudoLA_TLS_DESC_PC{,LARGE} sym).
4945 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
4946 return Large ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
4947 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
4948}
4949
4950SDValue
4951LoongArchTargetLowering::lowerGlobalTLSAddress(SDValue Op,
4952 SelectionDAG &DAG) const {
4955 report_fatal_error("In GHC calling convention TLS is not supported");
4956
4957 bool Large = DAG.getTarget().getCodeModel() == CodeModel::Large;
4958 assert((!Large || Subtarget.is64Bit()) && "Large code model requires LA64");
4959
4960 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
4961 assert(N->getOffset() == 0 && "unexpected offset in global node");
4962
4963 if (DAG.getTarget().useEmulatedTLS())
4964 reportFatalUsageError("the emulated TLS is prohibited");
4965
4966 bool IsDesc = DAG.getTarget().useTLSDESC();
4967
4968 switch (getTargetMachine().getTLSModel(N->getGlobal())) {
4970 // In this model, application code calls the dynamic linker function
4971 // __tls_get_addr to locate TLS offsets into the dynamic thread vector at
4972 // runtime.
4973 if (!IsDesc)
4974 return getDynamicTLSAddr(N, DAG,
4975 Large ? LoongArch::PseudoLA_TLS_GD_LARGE
4976 : LoongArch::PseudoLA_TLS_GD,
4977 Large);
4978 break;
4980 // Same as GeneralDynamic, except for assembly modifiers and relocation
4981 // records.
4982 if (!IsDesc)
4983 return getDynamicTLSAddr(N, DAG,
4984 Large ? LoongArch::PseudoLA_TLS_LD_LARGE
4985 : LoongArch::PseudoLA_TLS_LD,
4986 Large);
4987 break;
4989 // This model uses the GOT to resolve TLS offsets.
4990 return getStaticTLSAddr(N, DAG,
4991 Large ? LoongArch::PseudoLA_TLS_IE_LARGE
4992 : LoongArch::PseudoLA_TLS_IE,
4993 /*UseGOT=*/true, Large);
4995 // This model is used when static linking as the TLS offsets are resolved
4996 // during program linking.
4997 //
4998 // This node doesn't need an extra argument for the large code model.
4999 return getStaticTLSAddr(N, DAG, LoongArch::PseudoLA_TLS_LE,
5000 /*UseGOT=*/false, Large);
5001 }
5002
5003 return getTLSDescAddr(N, DAG,
5004 Large ? LoongArch::PseudoLA_TLS_DESC_LARGE
5005 : LoongArch::PseudoLA_TLS_DESC,
5006 Large);
5007}
5008
5009template <unsigned N>
5011 SelectionDAG &DAG, bool IsSigned = false) {
5012 auto *CImm = cast<ConstantSDNode>(Op->getOperand(ImmOp));
5013 // Check the ImmArg.
5014 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
5015 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
5016 DAG.getContext()->emitError(Op->getOperationName(0) +
5017 ": argument out of range.");
5018 return DAG.getNode(ISD::UNDEF, SDLoc(Op), Op.getValueType());
5019 }
5020 return SDValue();
5021}
5022
5023SDValue
5024LoongArchTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5025 SelectionDAG &DAG) const {
5026 switch (Op.getConstantOperandVal(0)) {
5027 default:
5028 return SDValue(); // Don't custom lower most intrinsics.
5029 case Intrinsic::thread_pointer: {
5030 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5031 return DAG.getRegister(LoongArch::R2, PtrVT);
5032 }
5033 case Intrinsic::loongarch_lsx_vpickve2gr_d:
5034 case Intrinsic::loongarch_lsx_vpickve2gr_du:
5035 case Intrinsic::loongarch_lsx_vreplvei_d:
5036 case Intrinsic::loongarch_lasx_xvrepl128vei_d:
5037 return checkIntrinsicImmArg<1>(Op, 2, DAG);
5038 case Intrinsic::loongarch_lsx_vreplvei_w:
5039 case Intrinsic::loongarch_lasx_xvrepl128vei_w:
5040 case Intrinsic::loongarch_lasx_xvpickve2gr_d:
5041 case Intrinsic::loongarch_lasx_xvpickve2gr_du:
5042 case Intrinsic::loongarch_lasx_xvpickve_d:
5043 case Intrinsic::loongarch_lasx_xvpickve_d_f:
5044 return checkIntrinsicImmArg<2>(Op, 2, DAG);
5045 case Intrinsic::loongarch_lasx_xvinsve0_d:
5046 return checkIntrinsicImmArg<2>(Op, 3, DAG);
5047 case Intrinsic::loongarch_lsx_vsat_b:
5048 case Intrinsic::loongarch_lsx_vsat_bu:
5049 case Intrinsic::loongarch_lsx_vrotri_b:
5050 case Intrinsic::loongarch_lsx_vsllwil_h_b:
5051 case Intrinsic::loongarch_lsx_vsllwil_hu_bu:
5052 case Intrinsic::loongarch_lsx_vsrlri_b:
5053 case Intrinsic::loongarch_lsx_vsrari_b:
5054 case Intrinsic::loongarch_lsx_vreplvei_h:
5055 case Intrinsic::loongarch_lasx_xvsat_b:
5056 case Intrinsic::loongarch_lasx_xvsat_bu:
5057 case Intrinsic::loongarch_lasx_xvrotri_b:
5058 case Intrinsic::loongarch_lasx_xvsllwil_h_b:
5059 case Intrinsic::loongarch_lasx_xvsllwil_hu_bu:
5060 case Intrinsic::loongarch_lasx_xvsrlri_b:
5061 case Intrinsic::loongarch_lasx_xvsrari_b:
5062 case Intrinsic::loongarch_lasx_xvrepl128vei_h:
5063 case Intrinsic::loongarch_lasx_xvpickve_w:
5064 case Intrinsic::loongarch_lasx_xvpickve_w_f:
5065 return checkIntrinsicImmArg<3>(Op, 2, DAG);
5066 case Intrinsic::loongarch_lasx_xvinsve0_w:
5067 return checkIntrinsicImmArg<3>(Op, 3, DAG);
5068 case Intrinsic::loongarch_lsx_vsat_h:
5069 case Intrinsic::loongarch_lsx_vsat_hu:
5070 case Intrinsic::loongarch_lsx_vrotri_h:
5071 case Intrinsic::loongarch_lsx_vsllwil_w_h:
5072 case Intrinsic::loongarch_lsx_vsllwil_wu_hu:
5073 case Intrinsic::loongarch_lsx_vsrlri_h:
5074 case Intrinsic::loongarch_lsx_vsrari_h:
5075 case Intrinsic::loongarch_lsx_vreplvei_b:
5076 case Intrinsic::loongarch_lasx_xvsat_h:
5077 case Intrinsic::loongarch_lasx_xvsat_hu:
5078 case Intrinsic::loongarch_lasx_xvrotri_h:
5079 case Intrinsic::loongarch_lasx_xvsllwil_w_h:
5080 case Intrinsic::loongarch_lasx_xvsllwil_wu_hu:
5081 case Intrinsic::loongarch_lasx_xvsrlri_h:
5082 case Intrinsic::loongarch_lasx_xvsrari_h:
5083 case Intrinsic::loongarch_lasx_xvrepl128vei_b:
5084 return checkIntrinsicImmArg<4>(Op, 2, DAG);
5085 case Intrinsic::loongarch_lsx_vsrlni_b_h:
5086 case Intrinsic::loongarch_lsx_vsrani_b_h:
5087 case Intrinsic::loongarch_lsx_vsrlrni_b_h:
5088 case Intrinsic::loongarch_lsx_vsrarni_b_h:
5089 case Intrinsic::loongarch_lsx_vssrlni_b_h:
5090 case Intrinsic::loongarch_lsx_vssrani_b_h:
5091 case Intrinsic::loongarch_lsx_vssrlni_bu_h:
5092 case Intrinsic::loongarch_lsx_vssrani_bu_h:
5093 case Intrinsic::loongarch_lsx_vssrlrni_b_h:
5094 case Intrinsic::loongarch_lsx_vssrarni_b_h:
5095 case Intrinsic::loongarch_lsx_vssrlrni_bu_h:
5096 case Intrinsic::loongarch_lsx_vssrarni_bu_h:
5097 case Intrinsic::loongarch_lasx_xvsrlni_b_h:
5098 case Intrinsic::loongarch_lasx_xvsrani_b_h:
5099 case Intrinsic::loongarch_lasx_xvsrlrni_b_h:
5100 case Intrinsic::loongarch_lasx_xvsrarni_b_h:
5101 case Intrinsic::loongarch_lasx_xvssrlni_b_h:
5102 case Intrinsic::loongarch_lasx_xvssrani_b_h:
5103 case Intrinsic::loongarch_lasx_xvssrlni_bu_h:
5104 case Intrinsic::loongarch_lasx_xvssrani_bu_h:
5105 case Intrinsic::loongarch_lasx_xvssrlrni_b_h:
5106 case Intrinsic::loongarch_lasx_xvssrarni_b_h:
5107 case Intrinsic::loongarch_lasx_xvssrlrni_bu_h:
5108 case Intrinsic::loongarch_lasx_xvssrarni_bu_h:
5109 return checkIntrinsicImmArg<4>(Op, 3, DAG);
5110 case Intrinsic::loongarch_lsx_vsat_w:
5111 case Intrinsic::loongarch_lsx_vsat_wu:
5112 case Intrinsic::loongarch_lsx_vrotri_w:
5113 case Intrinsic::loongarch_lsx_vsllwil_d_w:
5114 case Intrinsic::loongarch_lsx_vsllwil_du_wu:
5115 case Intrinsic::loongarch_lsx_vsrlri_w:
5116 case Intrinsic::loongarch_lsx_vsrari_w:
5117 case Intrinsic::loongarch_lsx_vslei_bu:
5118 case Intrinsic::loongarch_lsx_vslei_hu:
5119 case Intrinsic::loongarch_lsx_vslei_wu:
5120 case Intrinsic::loongarch_lsx_vslei_du:
5121 case Intrinsic::loongarch_lsx_vslti_bu:
5122 case Intrinsic::loongarch_lsx_vslti_hu:
5123 case Intrinsic::loongarch_lsx_vslti_wu:
5124 case Intrinsic::loongarch_lsx_vslti_du:
5125 case Intrinsic::loongarch_lsx_vbsll_v:
5126 case Intrinsic::loongarch_lsx_vbsrl_v:
5127 case Intrinsic::loongarch_lasx_xvsat_w:
5128 case Intrinsic::loongarch_lasx_xvsat_wu:
5129 case Intrinsic::loongarch_lasx_xvrotri_w:
5130 case Intrinsic::loongarch_lasx_xvsllwil_d_w:
5131 case Intrinsic::loongarch_lasx_xvsllwil_du_wu:
5132 case Intrinsic::loongarch_lasx_xvsrlri_w:
5133 case Intrinsic::loongarch_lasx_xvsrari_w:
5134 case Intrinsic::loongarch_lasx_xvslei_bu:
5135 case Intrinsic::loongarch_lasx_xvslei_hu:
5136 case Intrinsic::loongarch_lasx_xvslei_wu:
5137 case Intrinsic::loongarch_lasx_xvslei_du:
5138 case Intrinsic::loongarch_lasx_xvslti_bu:
5139 case Intrinsic::loongarch_lasx_xvslti_hu:
5140 case Intrinsic::loongarch_lasx_xvslti_wu:
5141 case Intrinsic::loongarch_lasx_xvslti_du:
5142 case Intrinsic::loongarch_lasx_xvbsll_v:
5143 case Intrinsic::loongarch_lasx_xvbsrl_v:
5144 return checkIntrinsicImmArg<5>(Op, 2, DAG);
5145 case Intrinsic::loongarch_lsx_vseqi_b:
5146 case Intrinsic::loongarch_lsx_vseqi_h:
5147 case Intrinsic::loongarch_lsx_vseqi_w:
5148 case Intrinsic::loongarch_lsx_vseqi_d:
5149 case Intrinsic::loongarch_lsx_vslei_b:
5150 case Intrinsic::loongarch_lsx_vslei_h:
5151 case Intrinsic::loongarch_lsx_vslei_w:
5152 case Intrinsic::loongarch_lsx_vslei_d:
5153 case Intrinsic::loongarch_lsx_vslti_b:
5154 case Intrinsic::loongarch_lsx_vslti_h:
5155 case Intrinsic::loongarch_lsx_vslti_w:
5156 case Intrinsic::loongarch_lsx_vslti_d:
5157 case Intrinsic::loongarch_lasx_xvseqi_b:
5158 case Intrinsic::loongarch_lasx_xvseqi_h:
5159 case Intrinsic::loongarch_lasx_xvseqi_w:
5160 case Intrinsic::loongarch_lasx_xvseqi_d:
5161 case Intrinsic::loongarch_lasx_xvslei_b:
5162 case Intrinsic::loongarch_lasx_xvslei_h:
5163 case Intrinsic::loongarch_lasx_xvslei_w:
5164 case Intrinsic::loongarch_lasx_xvslei_d:
5165 case Intrinsic::loongarch_lasx_xvslti_b:
5166 case Intrinsic::loongarch_lasx_xvslti_h:
5167 case Intrinsic::loongarch_lasx_xvslti_w:
5168 case Intrinsic::loongarch_lasx_xvslti_d:
5169 return checkIntrinsicImmArg<5>(Op, 2, DAG, /*IsSigned=*/true);
5170 case Intrinsic::loongarch_lsx_vsrlni_h_w:
5171 case Intrinsic::loongarch_lsx_vsrani_h_w:
5172 case Intrinsic::loongarch_lsx_vsrlrni_h_w:
5173 case Intrinsic::loongarch_lsx_vsrarni_h_w:
5174 case Intrinsic::loongarch_lsx_vssrlni_h_w:
5175 case Intrinsic::loongarch_lsx_vssrani_h_w:
5176 case Intrinsic::loongarch_lsx_vssrlni_hu_w:
5177 case Intrinsic::loongarch_lsx_vssrani_hu_w:
5178 case Intrinsic::loongarch_lsx_vssrlrni_h_w:
5179 case Intrinsic::loongarch_lsx_vssrarni_h_w:
5180 case Intrinsic::loongarch_lsx_vssrlrni_hu_w:
5181 case Intrinsic::loongarch_lsx_vssrarni_hu_w:
5182 case Intrinsic::loongarch_lsx_vfrstpi_b:
5183 case Intrinsic::loongarch_lsx_vfrstpi_h:
5184 case Intrinsic::loongarch_lasx_xvsrlni_h_w:
5185 case Intrinsic::loongarch_lasx_xvsrani_h_w:
5186 case Intrinsic::loongarch_lasx_xvsrlrni_h_w:
5187 case Intrinsic::loongarch_lasx_xvsrarni_h_w:
5188 case Intrinsic::loongarch_lasx_xvssrlni_h_w:
5189 case Intrinsic::loongarch_lasx_xvssrani_h_w:
5190 case Intrinsic::loongarch_lasx_xvssrlni_hu_w:
5191 case Intrinsic::loongarch_lasx_xvssrani_hu_w:
5192 case Intrinsic::loongarch_lasx_xvssrlrni_h_w:
5193 case Intrinsic::loongarch_lasx_xvssrarni_h_w:
5194 case Intrinsic::loongarch_lasx_xvssrlrni_hu_w:
5195 case Intrinsic::loongarch_lasx_xvssrarni_hu_w:
5196 case Intrinsic::loongarch_lasx_xvfrstpi_b:
5197 case Intrinsic::loongarch_lasx_xvfrstpi_h:
5198 return checkIntrinsicImmArg<5>(Op, 3, DAG);
5199 case Intrinsic::loongarch_lsx_vsat_d:
5200 case Intrinsic::loongarch_lsx_vsat_du:
5201 case Intrinsic::loongarch_lsx_vrotri_d:
5202 case Intrinsic::loongarch_lsx_vsrlri_d:
5203 case Intrinsic::loongarch_lsx_vsrari_d:
5204 case Intrinsic::loongarch_lasx_xvsat_d:
5205 case Intrinsic::loongarch_lasx_xvsat_du:
5206 case Intrinsic::loongarch_lasx_xvrotri_d:
5207 case Intrinsic::loongarch_lasx_xvsrlri_d:
5208 case Intrinsic::loongarch_lasx_xvsrari_d:
5209 return checkIntrinsicImmArg<6>(Op, 2, DAG);
5210 case Intrinsic::loongarch_lsx_vsrlni_w_d:
5211 case Intrinsic::loongarch_lsx_vsrani_w_d:
5212 case Intrinsic::loongarch_lsx_vsrlrni_w_d:
5213 case Intrinsic::loongarch_lsx_vsrarni_w_d:
5214 case Intrinsic::loongarch_lsx_vssrlni_w_d:
5215 case Intrinsic::loongarch_lsx_vssrani_w_d:
5216 case Intrinsic::loongarch_lsx_vssrlni_wu_d:
5217 case Intrinsic::loongarch_lsx_vssrani_wu_d:
5218 case Intrinsic::loongarch_lsx_vssrlrni_w_d:
5219 case Intrinsic::loongarch_lsx_vssrarni_w_d:
5220 case Intrinsic::loongarch_lsx_vssrlrni_wu_d:
5221 case Intrinsic::loongarch_lsx_vssrarni_wu_d:
5222 case Intrinsic::loongarch_lasx_xvsrlni_w_d:
5223 case Intrinsic::loongarch_lasx_xvsrani_w_d:
5224 case Intrinsic::loongarch_lasx_xvsrlrni_w_d:
5225 case Intrinsic::loongarch_lasx_xvsrarni_w_d:
5226 case Intrinsic::loongarch_lasx_xvssrlni_w_d:
5227 case Intrinsic::loongarch_lasx_xvssrani_w_d:
5228 case Intrinsic::loongarch_lasx_xvssrlni_wu_d:
5229 case Intrinsic::loongarch_lasx_xvssrani_wu_d:
5230 case Intrinsic::loongarch_lasx_xvssrlrni_w_d:
5231 case Intrinsic::loongarch_lasx_xvssrarni_w_d:
5232 case Intrinsic::loongarch_lasx_xvssrlrni_wu_d:
5233 case Intrinsic::loongarch_lasx_xvssrarni_wu_d:
5234 return checkIntrinsicImmArg<6>(Op, 3, DAG);
5235 case Intrinsic::loongarch_lsx_vsrlni_d_q:
5236 case Intrinsic::loongarch_lsx_vsrani_d_q:
5237 case Intrinsic::loongarch_lsx_vsrlrni_d_q:
5238 case Intrinsic::loongarch_lsx_vsrarni_d_q:
5239 case Intrinsic::loongarch_lsx_vssrlni_d_q:
5240 case Intrinsic::loongarch_lsx_vssrani_d_q:
5241 case Intrinsic::loongarch_lsx_vssrlni_du_q:
5242 case Intrinsic::loongarch_lsx_vssrani_du_q:
5243 case Intrinsic::loongarch_lsx_vssrlrni_d_q:
5244 case Intrinsic::loongarch_lsx_vssrarni_d_q:
5245 case Intrinsic::loongarch_lsx_vssrlrni_du_q:
5246 case Intrinsic::loongarch_lsx_vssrarni_du_q:
5247 case Intrinsic::loongarch_lasx_xvsrlni_d_q:
5248 case Intrinsic::loongarch_lasx_xvsrani_d_q:
5249 case Intrinsic::loongarch_lasx_xvsrlrni_d_q:
5250 case Intrinsic::loongarch_lasx_xvsrarni_d_q:
5251 case Intrinsic::loongarch_lasx_xvssrlni_d_q:
5252 case Intrinsic::loongarch_lasx_xvssrani_d_q:
5253 case Intrinsic::loongarch_lasx_xvssrlni_du_q:
5254 case Intrinsic::loongarch_lasx_xvssrani_du_q:
5255 case Intrinsic::loongarch_lasx_xvssrlrni_d_q:
5256 case Intrinsic::loongarch_lasx_xvssrarni_d_q:
5257 case Intrinsic::loongarch_lasx_xvssrlrni_du_q:
5258 case Intrinsic::loongarch_lasx_xvssrarni_du_q:
5259 return checkIntrinsicImmArg<7>(Op, 3, DAG);
5260 case Intrinsic::loongarch_lsx_vnori_b:
5261 case Intrinsic::loongarch_lsx_vshuf4i_b:
5262 case Intrinsic::loongarch_lsx_vshuf4i_h:
5263 case Intrinsic::loongarch_lsx_vshuf4i_w:
5264 case Intrinsic::loongarch_lasx_xvnori_b:
5265 case Intrinsic::loongarch_lasx_xvshuf4i_b:
5266 case Intrinsic::loongarch_lasx_xvshuf4i_h:
5267 case Intrinsic::loongarch_lasx_xvshuf4i_w:
5268 case Intrinsic::loongarch_lasx_xvpermi_d:
5269 return checkIntrinsicImmArg<8>(Op, 2, DAG);
5270 case Intrinsic::loongarch_lsx_vshuf4i_d:
5271 case Intrinsic::loongarch_lsx_vpermi_w:
5272 case Intrinsic::loongarch_lsx_vbitseli_b:
5273 case Intrinsic::loongarch_lsx_vextrins_b:
5274 case Intrinsic::loongarch_lsx_vextrins_h:
5275 case Intrinsic::loongarch_lsx_vextrins_w:
5276 case Intrinsic::loongarch_lsx_vextrins_d:
5277 case Intrinsic::loongarch_lasx_xvshuf4i_d:
5278 case Intrinsic::loongarch_lasx_xvpermi_w:
5279 case Intrinsic::loongarch_lasx_xvpermi_q:
5280 case Intrinsic::loongarch_lasx_xvbitseli_b:
5281 case Intrinsic::loongarch_lasx_xvextrins_b:
5282 case Intrinsic::loongarch_lasx_xvextrins_h:
5283 case Intrinsic::loongarch_lasx_xvextrins_w:
5284 case Intrinsic::loongarch_lasx_xvextrins_d:
5285 return checkIntrinsicImmArg<8>(Op, 3, DAG);
5286 case Intrinsic::loongarch_lsx_vrepli_b:
5287 case Intrinsic::loongarch_lsx_vrepli_h:
5288 case Intrinsic::loongarch_lsx_vrepli_w:
5289 case Intrinsic::loongarch_lsx_vrepli_d:
5290 case Intrinsic::loongarch_lasx_xvrepli_b:
5291 case Intrinsic::loongarch_lasx_xvrepli_h:
5292 case Intrinsic::loongarch_lasx_xvrepli_w:
5293 case Intrinsic::loongarch_lasx_xvrepli_d:
5294 return checkIntrinsicImmArg<10>(Op, 1, DAG, /*IsSigned=*/true);
5295 case Intrinsic::loongarch_lsx_vldi:
5296 case Intrinsic::loongarch_lasx_xvldi:
5297 return checkIntrinsicImmArg<13>(Op, 1, DAG, /*IsSigned=*/true);
5298 }
5299}
5300
5301// Helper function that emits error message for intrinsics with chain and return
5302// merge values of a UNDEF and the chain.
5304 StringRef ErrorMsg,
5305 SelectionDAG &DAG) {
5306 DAG.getContext()->emitError(Op->getOperationName(0) + ": " + ErrorMsg + ".");
5307 return DAG.getMergeValues({DAG.getUNDEF(Op.getValueType()), Op.getOperand(0)},
5308 SDLoc(Op));
5309}
5310
5311SDValue
5312LoongArchTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5313 SelectionDAG &DAG) const {
5314 SDLoc DL(Op);
5315 MVT GRLenVT = Subtarget.getGRLenVT();
5316 EVT VT = Op.getValueType();
5317 SDValue Chain = Op.getOperand(0);
5318 const StringRef ErrorMsgOOR = "argument out of range";
5319 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
5320 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
5321
5322 switch (Op.getConstantOperandVal(1)) {
5323 default:
5324 return Op;
5325 case Intrinsic::loongarch_crc_w_b_w:
5326 case Intrinsic::loongarch_crc_w_h_w:
5327 case Intrinsic::loongarch_crc_w_w_w:
5328 case Intrinsic::loongarch_crc_w_d_w:
5329 case Intrinsic::loongarch_crcc_w_b_w:
5330 case Intrinsic::loongarch_crcc_w_h_w:
5331 case Intrinsic::loongarch_crcc_w_w_w:
5332 case Intrinsic::loongarch_crcc_w_d_w:
5333 return emitIntrinsicWithChainErrorMessage(Op, ErrorMsgReqLA64, DAG);
5334 case Intrinsic::loongarch_csrrd_w:
5335 case Intrinsic::loongarch_csrrd_d: {
5336 unsigned Imm = Op.getConstantOperandVal(2);
5337 return !isUInt<14>(Imm)
5338 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5339 : DAG.getNode(LoongArchISD::CSRRD, DL, {GRLenVT, MVT::Other},
5340 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
5341 }
5342 case Intrinsic::loongarch_csrwr_w:
5343 case Intrinsic::loongarch_csrwr_d: {
5344 unsigned Imm = Op.getConstantOperandVal(3);
5345 return !isUInt<14>(Imm)
5346 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5347 : DAG.getNode(LoongArchISD::CSRWR, DL, {GRLenVT, MVT::Other},
5348 {Chain, Op.getOperand(2),
5349 DAG.getConstant(Imm, DL, GRLenVT)});
5350 }
5351 case Intrinsic::loongarch_csrxchg_w:
5352 case Intrinsic::loongarch_csrxchg_d: {
5353 unsigned Imm = Op.getConstantOperandVal(4);
5354 return !isUInt<14>(Imm)
5355 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5356 : DAG.getNode(LoongArchISD::CSRXCHG, DL, {GRLenVT, MVT::Other},
5357 {Chain, Op.getOperand(2), Op.getOperand(3),
5358 DAG.getConstant(Imm, DL, GRLenVT)});
5359 }
5360 case Intrinsic::loongarch_iocsrrd_d: {
5361 return DAG.getNode(
5362 LoongArchISD::IOCSRRD_D, DL, {GRLenVT, MVT::Other},
5363 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op.getOperand(2))});
5364 }
5365#define IOCSRRD_CASE(NAME, NODE) \
5366 case Intrinsic::loongarch_##NAME: { \
5367 return DAG.getNode(LoongArchISD::NODE, DL, {GRLenVT, MVT::Other}, \
5368 {Chain, Op.getOperand(2)}); \
5369 }
5370 IOCSRRD_CASE(iocsrrd_b, IOCSRRD_B);
5371 IOCSRRD_CASE(iocsrrd_h, IOCSRRD_H);
5372 IOCSRRD_CASE(iocsrrd_w, IOCSRRD_W);
5373#undef IOCSRRD_CASE
5374 case Intrinsic::loongarch_cpucfg: {
5375 return DAG.getNode(LoongArchISD::CPUCFG, DL, {GRLenVT, MVT::Other},
5376 {Chain, Op.getOperand(2)});
5377 }
5378 case Intrinsic::loongarch_lddir_d: {
5379 unsigned Imm = Op.getConstantOperandVal(3);
5380 return !isUInt<8>(Imm)
5381 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5382 : Op;
5383 }
5384 case Intrinsic::loongarch_movfcsr2gr: {
5385 if (!Subtarget.hasBasicF())
5386 return emitIntrinsicWithChainErrorMessage(Op, ErrorMsgReqF, DAG);
5387 unsigned Imm = Op.getConstantOperandVal(2);
5388 return !isUInt<2>(Imm)
5389 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5390 : DAG.getNode(LoongArchISD::MOVFCSR2GR, DL, {VT, MVT::Other},
5391 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
5392 }
5393 case Intrinsic::loongarch_lsx_vld:
5394 case Intrinsic::loongarch_lsx_vldrepl_b:
5395 case Intrinsic::loongarch_lasx_xvld:
5396 case Intrinsic::loongarch_lasx_xvldrepl_b:
5397 return !isInt<12>(cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5398 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5399 : SDValue();
5400 case Intrinsic::loongarch_lsx_vldrepl_h:
5401 case Intrinsic::loongarch_lasx_xvldrepl_h:
5402 return !isShiftedInt<11, 1>(
5403 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5405 Op, "argument out of range or not a multiple of 2", DAG)
5406 : SDValue();
5407 case Intrinsic::loongarch_lsx_vldrepl_w:
5408 case Intrinsic::loongarch_lasx_xvldrepl_w:
5409 return !isShiftedInt<10, 2>(
5410 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5412 Op, "argument out of range or not a multiple of 4", DAG)
5413 : SDValue();
5414 case Intrinsic::loongarch_lsx_vldrepl_d:
5415 case Intrinsic::loongarch_lasx_xvldrepl_d:
5416 return !isShiftedInt<9, 3>(
5417 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5419 Op, "argument out of range or not a multiple of 8", DAG)
5420 : SDValue();
5421 }
5422}
5423
5424// Helper function that emits error message for intrinsics with void return
5425// value and return the chain.
5427 SelectionDAG &DAG) {
5428
5429 DAG.getContext()->emitError(Op->getOperationName(0) + ": " + ErrorMsg + ".");
5430 return Op.getOperand(0);
5431}
5432
5433SDValue LoongArchTargetLowering::lowerINTRINSIC_VOID(SDValue Op,
5434 SelectionDAG &DAG) const {
5435 SDLoc DL(Op);
5436 MVT GRLenVT = Subtarget.getGRLenVT();
5437 SDValue Chain = Op.getOperand(0);
5438 uint64_t IntrinsicEnum = Op.getConstantOperandVal(1);
5439 SDValue Op2 = Op.getOperand(2);
5440 const StringRef ErrorMsgOOR = "argument out of range";
5441 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
5442 const StringRef ErrorMsgReqLA32 = "requires loongarch32";
5443 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
5444
5445 switch (IntrinsicEnum) {
5446 default:
5447 // TODO: Add more Intrinsics.
5448 return SDValue();
5449 case Intrinsic::loongarch_cacop_d:
5450 case Intrinsic::loongarch_cacop_w: {
5451 if (IntrinsicEnum == Intrinsic::loongarch_cacop_d && !Subtarget.is64Bit())
5452 return emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG);
5453 if (IntrinsicEnum == Intrinsic::loongarch_cacop_w && Subtarget.is64Bit())
5454 return emitIntrinsicErrorMessage(Op, ErrorMsgReqLA32, DAG);
5455 // call void @llvm.loongarch.cacop.[d/w](uimm5, rj, simm12)
5456 unsigned Imm1 = Op2->getAsZExtVal();
5457 int Imm2 = cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue();
5458 if (!isUInt<5>(Imm1) || !isInt<12>(Imm2))
5459 return emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG);
5460 return Op;
5461 }
5462 case Intrinsic::loongarch_dbar: {
5463 unsigned Imm = Op2->getAsZExtVal();
5464 return !isUInt<15>(Imm)
5465 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5466 : DAG.getNode(LoongArchISD::DBAR, DL, MVT::Other, Chain,
5467 DAG.getConstant(Imm, DL, GRLenVT));
5468 }
5469 case Intrinsic::loongarch_ibar: {
5470 unsigned Imm = Op2->getAsZExtVal();
5471 return !isUInt<15>(Imm)
5472 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5473 : DAG.getNode(LoongArchISD::IBAR, DL, MVT::Other, Chain,
5474 DAG.getConstant(Imm, DL, GRLenVT));
5475 }
5476 case Intrinsic::loongarch_break: {
5477 unsigned Imm = Op2->getAsZExtVal();
5478 return !isUInt<15>(Imm)
5479 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5480 : DAG.getNode(LoongArchISD::BREAK, DL, MVT::Other, Chain,
5481 DAG.getConstant(Imm, DL, GRLenVT));
5482 }
5483 case Intrinsic::loongarch_movgr2fcsr: {
5484 if (!Subtarget.hasBasicF())
5485 return emitIntrinsicErrorMessage(Op, ErrorMsgReqF, DAG);
5486 unsigned Imm = Op2->getAsZExtVal();
5487 return !isUInt<2>(Imm)
5488 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5489 : DAG.getNode(LoongArchISD::MOVGR2FCSR, DL, MVT::Other, Chain,
5490 DAG.getConstant(Imm, DL, GRLenVT),
5491 DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT,
5492 Op.getOperand(3)));
5493 }
5494 case Intrinsic::loongarch_syscall: {
5495 unsigned Imm = Op2->getAsZExtVal();
5496 return !isUInt<15>(Imm)
5497 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5498 : DAG.getNode(LoongArchISD::SYSCALL, DL, MVT::Other, Chain,
5499 DAG.getConstant(Imm, DL, GRLenVT));
5500 }
5501#define IOCSRWR_CASE(NAME, NODE) \
5502 case Intrinsic::loongarch_##NAME: { \
5503 SDValue Op3 = Op.getOperand(3); \
5504 return Subtarget.is64Bit() \
5505 ? DAG.getNode(LoongArchISD::NODE, DL, MVT::Other, Chain, \
5506 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2), \
5507 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op3)) \
5508 : DAG.getNode(LoongArchISD::NODE, DL, MVT::Other, Chain, Op2, \
5509 Op3); \
5510 }
5511 IOCSRWR_CASE(iocsrwr_b, IOCSRWR_B);
5512 IOCSRWR_CASE(iocsrwr_h, IOCSRWR_H);
5513 IOCSRWR_CASE(iocsrwr_w, IOCSRWR_W);
5514#undef IOCSRWR_CASE
5515 case Intrinsic::loongarch_iocsrwr_d: {
5516 return !Subtarget.is64Bit()
5517 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG)
5518 : DAG.getNode(LoongArchISD::IOCSRWR_D, DL, MVT::Other, Chain,
5519 Op2,
5520 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
5521 Op.getOperand(3)));
5522 }
5523#define ASRT_LE_GT_CASE(NAME) \
5524 case Intrinsic::loongarch_##NAME: { \
5525 return !Subtarget.is64Bit() \
5526 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG) \
5527 : Op; \
5528 }
5529 ASRT_LE_GT_CASE(asrtle_d)
5530 ASRT_LE_GT_CASE(asrtgt_d)
5531#undef ASRT_LE_GT_CASE
5532 case Intrinsic::loongarch_ldpte_d: {
5533 unsigned Imm = Op.getConstantOperandVal(3);
5534 return !Subtarget.is64Bit()
5535 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG)
5536 : !isUInt<8>(Imm) ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5537 : Op;
5538 }
5539 case Intrinsic::loongarch_lsx_vst:
5540 case Intrinsic::loongarch_lasx_xvst:
5541 return !isInt<12>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue())
5542 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5543 : SDValue();
5544 case Intrinsic::loongarch_lasx_xvstelm_b:
5545 return (!isInt<8>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5546 !isUInt<5>(Op.getConstantOperandVal(5)))
5547 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5548 : SDValue();
5549 case Intrinsic::loongarch_lsx_vstelm_b:
5550 return (!isInt<8>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5551 !isUInt<4>(Op.getConstantOperandVal(5)))
5552 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5553 : SDValue();
5554 case Intrinsic::loongarch_lasx_xvstelm_h:
5555 return (!isShiftedInt<8, 1>(
5556 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5557 !isUInt<4>(Op.getConstantOperandVal(5)))
5559 Op, "argument out of range or not a multiple of 2", DAG)
5560 : SDValue();
5561 case Intrinsic::loongarch_lsx_vstelm_h:
5562 return (!isShiftedInt<8, 1>(
5563 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5564 !isUInt<3>(Op.getConstantOperandVal(5)))
5566 Op, "argument out of range or not a multiple of 2", DAG)
5567 : SDValue();
5568 case Intrinsic::loongarch_lasx_xvstelm_w:
5569 return (!isShiftedInt<8, 2>(
5570 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5571 !isUInt<3>(Op.getConstantOperandVal(5)))
5573 Op, "argument out of range or not a multiple of 4", DAG)
5574 : SDValue();
5575 case Intrinsic::loongarch_lsx_vstelm_w:
5576 return (!isShiftedInt<8, 2>(
5577 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5578 !isUInt<2>(Op.getConstantOperandVal(5)))
5580 Op, "argument out of range or not a multiple of 4", DAG)
5581 : SDValue();
5582 case Intrinsic::loongarch_lasx_xvstelm_d:
5583 return (!isShiftedInt<8, 3>(
5584 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5585 !isUInt<2>(Op.getConstantOperandVal(5)))
5587 Op, "argument out of range or not a multiple of 8", DAG)
5588 : SDValue();
5589 case Intrinsic::loongarch_lsx_vstelm_d:
5590 return (!isShiftedInt<8, 3>(
5591 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5592 !isUInt<1>(Op.getConstantOperandVal(5)))
5594 Op, "argument out of range or not a multiple of 8", DAG)
5595 : SDValue();
5596 }
5597}
5598
5599SDValue LoongArchTargetLowering::lowerShiftLeftParts(SDValue Op,
5600 SelectionDAG &DAG) const {
5601 SDLoc DL(Op);
5602 SDValue Lo = Op.getOperand(0);
5603 SDValue Hi = Op.getOperand(1);
5604 SDValue Shamt = Op.getOperand(2);
5605 EVT VT = Lo.getValueType();
5606
5607 // if Shamt-GRLen < 0: // Shamt < GRLen
5608 // Lo = Lo << Shamt
5609 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (GRLen-1 ^ Shamt))
5610 // else:
5611 // Lo = 0
5612 // Hi = Lo << (Shamt-GRLen)
5613
5614 SDValue Zero = DAG.getConstant(0, DL, VT);
5615 SDValue One = DAG.getConstant(1, DL, VT);
5616 SDValue MinusGRLen =
5617 DAG.getSignedConstant(-(int)Subtarget.getGRLen(), DL, VT);
5618 SDValue GRLenMinus1 = DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT);
5619 SDValue ShamtMinusGRLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusGRLen);
5620 SDValue GRLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, GRLenMinus1);
5621
5622 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
5623 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
5624 SDValue ShiftRightLo =
5625 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, GRLenMinus1Shamt);
5626 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
5627 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
5628 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusGRLen);
5629
5630 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusGRLen, Zero, ISD::SETLT);
5631
5632 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
5633 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
5634
5635 SDValue Parts[2] = {Lo, Hi};
5636 return DAG.getMergeValues(Parts, DL);
5637}
5638
5639SDValue LoongArchTargetLowering::lowerShiftRightParts(SDValue Op,
5640 SelectionDAG &DAG,
5641 bool IsSRA) const {
5642 SDLoc DL(Op);
5643 SDValue Lo = Op.getOperand(0);
5644 SDValue Hi = Op.getOperand(1);
5645 SDValue Shamt = Op.getOperand(2);
5646 EVT VT = Lo.getValueType();
5647
5648 // SRA expansion:
5649 // if Shamt-GRLen < 0: // Shamt < GRLen
5650 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ GRLen-1))
5651 // Hi = Hi >>s Shamt
5652 // else:
5653 // Lo = Hi >>s (Shamt-GRLen);
5654 // Hi = Hi >>s (GRLen-1)
5655 //
5656 // SRL expansion:
5657 // if Shamt-GRLen < 0: // Shamt < GRLen
5658 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ GRLen-1))
5659 // Hi = Hi >>u Shamt
5660 // else:
5661 // Lo = Hi >>u (Shamt-GRLen);
5662 // Hi = 0;
5663
5664 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
5665
5666 SDValue Zero = DAG.getConstant(0, DL, VT);
5667 SDValue One = DAG.getConstant(1, DL, VT);
5668 SDValue MinusGRLen =
5669 DAG.getSignedConstant(-(int)Subtarget.getGRLen(), DL, VT);
5670 SDValue GRLenMinus1 = DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT);
5671 SDValue ShamtMinusGRLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusGRLen);
5672 SDValue GRLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, GRLenMinus1);
5673
5674 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
5675 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
5676 SDValue ShiftLeftHi =
5677 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, GRLenMinus1Shamt);
5678 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
5679 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
5680 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusGRLen);
5681 SDValue HiFalse =
5682 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, GRLenMinus1) : Zero;
5683
5684 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusGRLen, Zero, ISD::SETLT);
5685
5686 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
5687 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
5688
5689 SDValue Parts[2] = {Lo, Hi};
5690 return DAG.getMergeValues(Parts, DL);
5691}
5692
5693// Returns the opcode of the target-specific SDNode that implements the 32-bit
5694// form of the given Opcode.
5695static unsigned getLoongArchWOpcode(unsigned Opcode) {
5696 switch (Opcode) {
5697 default:
5698 llvm_unreachable("Unexpected opcode");
5699 case ISD::SDIV:
5700 return LoongArchISD::DIV_W;
5701 case ISD::UDIV:
5702 return LoongArchISD::DIV_WU;
5703 case ISD::SREM:
5704 return LoongArchISD::MOD_W;
5705 case ISD::UREM:
5706 return LoongArchISD::MOD_WU;
5707 case ISD::SHL:
5708 return LoongArchISD::SLL_W;
5709 case ISD::SRA:
5710 return LoongArchISD::SRA_W;
5711 case ISD::SRL:
5712 return LoongArchISD::SRL_W;
5713 case ISD::ROTL:
5714 case ISD::ROTR:
5715 return LoongArchISD::ROTR_W;
5716 case ISD::CTTZ:
5717 return LoongArchISD::CTZ_W;
5718 case ISD::CTLZ:
5719 return LoongArchISD::CLZ_W;
5720 }
5721}
5722
5723// Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5724// node. Because i8/i16/i32 isn't a legal type for LA64, these operations would
5725// otherwise be promoted to i64, making it difficult to select the
5726// SLL_W/.../*W later one because the fact the operation was originally of
5727// type i8/i16/i32 is lost.
5729 unsigned ExtOpc = ISD::ANY_EXTEND) {
5730 SDLoc DL(N);
5731 unsigned WOpcode = getLoongArchWOpcode(N->getOpcode());
5732 SDValue NewOp0, NewRes;
5733
5734 switch (NumOp) {
5735 default:
5736 llvm_unreachable("Unexpected NumOp");
5737 case 1: {
5738 NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5739 NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0);
5740 break;
5741 }
5742 case 2: {
5743 NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5744 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5745 if (N->getOpcode() == ISD::ROTL) {
5746 SDValue TmpOp = DAG.getConstant(32, DL, MVT::i64);
5747 NewOp1 = DAG.getNode(ISD::SUB, DL, MVT::i64, TmpOp, NewOp1);
5748 }
5749 NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5750 break;
5751 }
5752 // TODO:Handle more NumOp.
5753 }
5754
5755 // ReplaceNodeResults requires we maintain the same type for the return
5756 // value.
5757 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5758}
5759
5760// Converts the given 32-bit operation to a i64 operation with signed extension
5761// semantic to reduce the signed extension instructions.
5763 SDLoc DL(N);
5764 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5765 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5766 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5767 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5768 DAG.getValueType(MVT::i32));
5769 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5770}
5771
5772// Helper function that emits error message for intrinsics with/without chain
5773// and return a UNDEF or and the chain as the results.
5776 StringRef ErrorMsg, bool WithChain = true) {
5777 DAG.getContext()->emitError(N->getOperationName(0) + ": " + ErrorMsg + ".");
5778 Results.push_back(DAG.getUNDEF(N->getValueType(0)));
5779 if (!WithChain)
5780 return;
5781 Results.push_back(N->getOperand(0));
5782}
5783
5784template <unsigned N>
5785static void
5788 unsigned ResOp) {
5789 const StringRef ErrorMsgOOR = "argument out of range";
5790 unsigned Imm = Node->getConstantOperandVal(2);
5791 if (!isUInt<N>(Imm)) {
5793 /*WithChain=*/false);
5794 return;
5795 }
5796 SDLoc DL(Node);
5797 SDValue Vec = Node->getOperand(1);
5798
5799 SDValue PickElt =
5800 DAG.getNode(ResOp, DL, Subtarget.getGRLenVT(), Vec,
5801 DAG.getConstant(Imm, DL, Subtarget.getGRLenVT()),
5803 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, Node->getValueType(0),
5804 PickElt.getValue(0)));
5805}
5806
5809 SelectionDAG &DAG,
5811 unsigned ResOp) {
5812 SDLoc DL(N);
5813 SDValue Vec = N->getOperand(1);
5814
5815 SDValue CB = DAG.getNode(ResOp, DL, Subtarget.getGRLenVT(), Vec);
5816 Results.push_back(
5817 DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), CB.getValue(0)));
5818}
5819
5820static void
5822 SelectionDAG &DAG,
5824 switch (N->getConstantOperandVal(0)) {
5825 default:
5826 llvm_unreachable("Unexpected Intrinsic.");
5827 case Intrinsic::loongarch_lsx_vpickve2gr_b:
5829 LoongArchISD::VPICK_SEXT_ELT);
5830 break;
5831 case Intrinsic::loongarch_lsx_vpickve2gr_h:
5832 case Intrinsic::loongarch_lasx_xvpickve2gr_w:
5834 LoongArchISD::VPICK_SEXT_ELT);
5835 break;
5836 case Intrinsic::loongarch_lsx_vpickve2gr_w:
5838 LoongArchISD::VPICK_SEXT_ELT);
5839 break;
5840 case Intrinsic::loongarch_lsx_vpickve2gr_bu:
5842 LoongArchISD::VPICK_ZEXT_ELT);
5843 break;
5844 case Intrinsic::loongarch_lsx_vpickve2gr_hu:
5845 case Intrinsic::loongarch_lasx_xvpickve2gr_wu:
5847 LoongArchISD::VPICK_ZEXT_ELT);
5848 break;
5849 case Intrinsic::loongarch_lsx_vpickve2gr_wu:
5851 LoongArchISD::VPICK_ZEXT_ELT);
5852 break;
5853 case Intrinsic::loongarch_lsx_bz_b:
5854 case Intrinsic::loongarch_lsx_bz_h:
5855 case Intrinsic::loongarch_lsx_bz_w:
5856 case Intrinsic::loongarch_lsx_bz_d:
5857 case Intrinsic::loongarch_lasx_xbz_b:
5858 case Intrinsic::loongarch_lasx_xbz_h:
5859 case Intrinsic::loongarch_lasx_xbz_w:
5860 case Intrinsic::loongarch_lasx_xbz_d:
5862 LoongArchISD::VALL_ZERO);
5863 break;
5864 case Intrinsic::loongarch_lsx_bz_v:
5865 case Intrinsic::loongarch_lasx_xbz_v:
5867 LoongArchISD::VANY_ZERO);
5868 break;
5869 case Intrinsic::loongarch_lsx_bnz_b:
5870 case Intrinsic::loongarch_lsx_bnz_h:
5871 case Intrinsic::loongarch_lsx_bnz_w:
5872 case Intrinsic::loongarch_lsx_bnz_d:
5873 case Intrinsic::loongarch_lasx_xbnz_b:
5874 case Intrinsic::loongarch_lasx_xbnz_h:
5875 case Intrinsic::loongarch_lasx_xbnz_w:
5876 case Intrinsic::loongarch_lasx_xbnz_d:
5878 LoongArchISD::VALL_NONZERO);
5879 break;
5880 case Intrinsic::loongarch_lsx_bnz_v:
5881 case Intrinsic::loongarch_lasx_xbnz_v:
5883 LoongArchISD::VANY_NONZERO);
5884 break;
5885 }
5886}
5887
5890 SelectionDAG &DAG) {
5891 assert(N->getValueType(0) == MVT::i128 &&
5892 "AtomicCmpSwap on types less than 128 should be legal");
5893 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
5894
5895 unsigned Opcode;
5896 switch (MemOp->getMergedOrdering()) {
5900 Opcode = LoongArch::PseudoCmpXchg128Acquire;
5901 break;
5904 Opcode = LoongArch::PseudoCmpXchg128;
5905 break;
5906 default:
5907 llvm_unreachable("Unexpected ordering!");
5908 }
5909
5910 SDLoc DL(N);
5911 auto CmpVal = DAG.SplitScalar(N->getOperand(2), DL, MVT::i64, MVT::i64);
5912 auto NewVal = DAG.SplitScalar(N->getOperand(3), DL, MVT::i64, MVT::i64);
5913 SDValue Ops[] = {N->getOperand(1), CmpVal.first, CmpVal.second,
5914 NewVal.first, NewVal.second, N->getOperand(0)};
5915
5916 SDNode *CmpSwap = DAG.getMachineNode(
5917 Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i64, MVT::Other),
5918 Ops);
5919 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
5920 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
5921 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
5922 Results.push_back(SDValue(CmpSwap, 3));
5923}
5924
5927 SDLoc DL(N);
5928 EVT VT = N->getValueType(0);
5929 switch (N->getOpcode()) {
5930 default:
5931 llvm_unreachable("Don't know how to legalize this operation");
5932 case ISD::ADD:
5933 case ISD::SUB:
5934 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5935 "Unexpected custom legalisation");
5936 Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5937 break;
5938 case ISD::SDIV:
5939 case ISD::UDIV:
5940 case ISD::SREM:
5941 case ISD::UREM:
5942 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
5943 "Unexpected custom legalisation");
5944 Results.push_back(customLegalizeToWOp(N, DAG, 2,
5945 Subtarget.hasDiv32() && VT == MVT::i32
5947 : ISD::SIGN_EXTEND));
5948 break;
5949 case ISD::SHL:
5950 case ISD::SRA:
5951 case ISD::SRL:
5952 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
5953 "Unexpected custom legalisation");
5954 if (N->getOperand(1).getOpcode() != ISD::Constant) {
5955 Results.push_back(customLegalizeToWOp(N, DAG, 2));
5956 break;
5957 }
5958 break;
5959 case ISD::ROTL:
5960 case ISD::ROTR:
5961 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
5962 "Unexpected custom legalisation");
5963 Results.push_back(customLegalizeToWOp(N, DAG, 2));
5964 break;
5965 case ISD::LOAD: {
5966 // Use an f64 load and a scalar_to_vector for v2f32 loads. This avoids
5967 // scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
5968 // cast since type legalization will try to use an i64 load.
5969 MVT VT = N->getSimpleValueType(0);
5970 assert(VT == MVT::v2f32 && Subtarget.hasExtLSX() &&
5971 "Unexpected custom legalisation");
5973 "Unexpected type action!");
5974 if (!ISD::isNON_EXTLoad(N))
5975 return;
5976 auto *Ld = cast<LoadSDNode>(N);
5977 SDValue Res = DAG.getLoad(MVT::f64, DL, Ld->getChain(), Ld->getBasePtr(),
5978 Ld->getPointerInfo(), Ld->getBaseAlign(),
5979 Ld->getMemOperand()->getFlags());
5980 SDValue Chain = Res.getValue(1);
5981 MVT VecVT = MVT::getVectorVT(MVT::f64, 2);
5982 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Res);
5983 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
5984 Res = DAG.getBitcast(WideVT, Res);
5985 Results.push_back(Res);
5986 Results.push_back(Chain);
5987 break;
5988 }
5989 case ISD::FP_TO_SINT: {
5990 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
5991 "Unexpected custom legalisation");
5992 SDValue Src = N->getOperand(0);
5993 EVT FVT = EVT::getFloatingPointVT(N->getValueSizeInBits(0));
5994 if (getTypeAction(*DAG.getContext(), Src.getValueType()) !=
5996 if (!isTypeLegal(Src.getValueType()))
5997 return;
5998 if (Src.getValueType() == MVT::f16)
5999 Src = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
6000 SDValue Dst = DAG.getNode(LoongArchISD::FTINT, DL, FVT, Src);
6001 Results.push_back(DAG.getNode(ISD::BITCAST, DL, VT, Dst));
6002 return;
6003 }
6004 // If the FP type needs to be softened, emit a library call using the 'si'
6005 // version. If we left it to default legalization we'd end up with 'di'.
6006 RTLIB::Libcall LC;
6007 LC = RTLIB::getFPTOSINT(Src.getValueType(), VT);
6008 MakeLibCallOptions CallOptions;
6009 EVT OpVT = Src.getValueType();
6010 CallOptions.setTypeListBeforeSoften(OpVT, VT);
6011 SDValue Chain = SDValue();
6012 SDValue Result;
6013 std::tie(Result, Chain) =
6014 makeLibCall(DAG, LC, VT, Src, CallOptions, DL, Chain);
6015 Results.push_back(Result);
6016 break;
6017 }
6018 case ISD::BITCAST: {
6019 SDValue Src = N->getOperand(0);
6020 EVT SrcVT = Src.getValueType();
6021 if (VT == MVT::i32 && SrcVT == MVT::f32 && Subtarget.is64Bit() &&
6022 Subtarget.hasBasicF()) {
6023 SDValue Dst =
6024 DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Src);
6025 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Dst));
6026 } else if (VT == MVT::i64 && SrcVT == MVT::f64 && !Subtarget.is64Bit()) {
6027 SDValue NewReg = DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
6028 DAG.getVTList(MVT::i32, MVT::i32), Src);
6029 SDValue RetReg = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6030 NewReg.getValue(0), NewReg.getValue(1));
6031 Results.push_back(RetReg);
6032 }
6033 break;
6034 }
6035 case ISD::FP_TO_UINT: {
6036 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6037 "Unexpected custom legalisation");
6038 auto &TLI = DAG.getTargetLoweringInfo();
6039 SDValue Tmp1, Tmp2;
6040 TLI.expandFP_TO_UINT(N, Tmp1, Tmp2, DAG);
6041 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Tmp1));
6042 break;
6043 }
6044 case ISD::FP_ROUND: {
6045 assert(VT == MVT::v2f32 && Subtarget.hasExtLSX() &&
6046 "Unexpected custom legalisation");
6047 // On LSX platforms, rounding from v2f64 to v4f32 (after legalization from
6048 // v2f32) is scalarized. Add a customized v2f32 widening to convert it into
6049 // a target-specific LoongArchISD::VFCVT to optimize it.
6050 SDValue Op0 = N->getOperand(0);
6051 EVT OpVT = Op0.getValueType();
6052 if (OpVT == MVT::v2f64) {
6053 SDValue Undef = DAG.getUNDEF(OpVT);
6054 SDValue Dst =
6055 DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32, Undef, Op0);
6056 Results.push_back(Dst);
6057 }
6058 break;
6059 }
6060 case ISD::BSWAP: {
6061 SDValue Src = N->getOperand(0);
6062 assert((VT == MVT::i16 || VT == MVT::i32) &&
6063 "Unexpected custom legalization");
6064 MVT GRLenVT = Subtarget.getGRLenVT();
6065 SDValue NewSrc = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, Src);
6066 SDValue Tmp;
6067 switch (VT.getSizeInBits()) {
6068 default:
6069 llvm_unreachable("Unexpected operand width");
6070 case 16:
6071 Tmp = DAG.getNode(LoongArchISD::REVB_2H, DL, GRLenVT, NewSrc);
6072 break;
6073 case 32:
6074 // Only LA64 will get to here due to the size mismatch between VT and
6075 // GRLenVT, LA32 lowering is directly defined in LoongArchInstrInfo.
6076 Tmp = DAG.getNode(LoongArchISD::REVB_2W, DL, GRLenVT, NewSrc);
6077 break;
6078 }
6079 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Tmp));
6080 break;
6081 }
6082 case ISD::BITREVERSE: {
6083 SDValue Src = N->getOperand(0);
6084 assert((VT == MVT::i8 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6085 "Unexpected custom legalization");
6086 MVT GRLenVT = Subtarget.getGRLenVT();
6087 SDValue NewSrc = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, Src);
6088 SDValue Tmp;
6089 switch (VT.getSizeInBits()) {
6090 default:
6091 llvm_unreachable("Unexpected operand width");
6092 case 8:
6093 Tmp = DAG.getNode(LoongArchISD::BITREV_4B, DL, GRLenVT, NewSrc);
6094 break;
6095 case 32:
6096 Tmp = DAG.getNode(LoongArchISD::BITREV_W, DL, GRLenVT, NewSrc);
6097 break;
6098 }
6099 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Tmp));
6100 break;
6101 }
6102 case ISD::CTLZ:
6103 case ISD::CTTZ: {
6104 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6105 "Unexpected custom legalisation");
6106 Results.push_back(customLegalizeToWOp(N, DAG, 1));
6107 break;
6108 }
6110 SDValue Chain = N->getOperand(0);
6111 SDValue Op2 = N->getOperand(2);
6112 MVT GRLenVT = Subtarget.getGRLenVT();
6113 const StringRef ErrorMsgOOR = "argument out of range";
6114 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
6115 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
6116
6117 switch (N->getConstantOperandVal(1)) {
6118 default:
6119 llvm_unreachable("Unexpected Intrinsic.");
6120 case Intrinsic::loongarch_movfcsr2gr: {
6121 if (!Subtarget.hasBasicF()) {
6122 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqF);
6123 return;
6124 }
6125 unsigned Imm = Op2->getAsZExtVal();
6126 if (!isUInt<2>(Imm)) {
6127 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6128 return;
6129 }
6130 SDValue MOVFCSR2GRResults = DAG.getNode(
6131 LoongArchISD::MOVFCSR2GR, SDLoc(N), {MVT::i64, MVT::Other},
6132 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
6133 Results.push_back(
6134 DAG.getNode(ISD::TRUNCATE, DL, VT, MOVFCSR2GRResults.getValue(0)));
6135 Results.push_back(MOVFCSR2GRResults.getValue(1));
6136 break;
6137 }
6138#define CRC_CASE_EXT_BINARYOP(NAME, NODE) \
6139 case Intrinsic::loongarch_##NAME: { \
6140 SDValue NODE = DAG.getNode( \
6141 LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6142 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2), \
6143 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3))}); \
6144 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NODE.getValue(0))); \
6145 Results.push_back(NODE.getValue(1)); \
6146 break; \
6147 }
6148 CRC_CASE_EXT_BINARYOP(crc_w_b_w, CRC_W_B_W)
6149 CRC_CASE_EXT_BINARYOP(crc_w_h_w, CRC_W_H_W)
6150 CRC_CASE_EXT_BINARYOP(crc_w_w_w, CRC_W_W_W)
6151 CRC_CASE_EXT_BINARYOP(crcc_w_b_w, CRCC_W_B_W)
6152 CRC_CASE_EXT_BINARYOP(crcc_w_h_w, CRCC_W_H_W)
6153 CRC_CASE_EXT_BINARYOP(crcc_w_w_w, CRCC_W_W_W)
6154#undef CRC_CASE_EXT_BINARYOP
6155
6156#define CRC_CASE_EXT_UNARYOP(NAME, NODE) \
6157 case Intrinsic::loongarch_##NAME: { \
6158 SDValue NODE = DAG.getNode( \
6159 LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6160 {Chain, Op2, \
6161 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3))}); \
6162 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NODE.getValue(0))); \
6163 Results.push_back(NODE.getValue(1)); \
6164 break; \
6165 }
6166 CRC_CASE_EXT_UNARYOP(crc_w_d_w, CRC_W_D_W)
6167 CRC_CASE_EXT_UNARYOP(crcc_w_d_w, CRCC_W_D_W)
6168#undef CRC_CASE_EXT_UNARYOP
6169#define CSR_CASE(ID) \
6170 case Intrinsic::loongarch_##ID: { \
6171 if (!Subtarget.is64Bit()) \
6172 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqLA64); \
6173 break; \
6174 }
6175 CSR_CASE(csrrd_d);
6176 CSR_CASE(csrwr_d);
6177 CSR_CASE(csrxchg_d);
6178 CSR_CASE(iocsrrd_d);
6179#undef CSR_CASE
6180 case Intrinsic::loongarch_csrrd_w: {
6181 unsigned Imm = Op2->getAsZExtVal();
6182 if (!isUInt<14>(Imm)) {
6183 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6184 return;
6185 }
6186 SDValue CSRRDResults =
6187 DAG.getNode(LoongArchISD::CSRRD, DL, {GRLenVT, MVT::Other},
6188 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
6189 Results.push_back(
6190 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRRDResults.getValue(0)));
6191 Results.push_back(CSRRDResults.getValue(1));
6192 break;
6193 }
6194 case Intrinsic::loongarch_csrwr_w: {
6195 unsigned Imm = N->getConstantOperandVal(3);
6196 if (!isUInt<14>(Imm)) {
6197 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6198 return;
6199 }
6200 SDValue CSRWRResults =
6201 DAG.getNode(LoongArchISD::CSRWR, DL, {GRLenVT, MVT::Other},
6202 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2),
6203 DAG.getConstant(Imm, DL, GRLenVT)});
6204 Results.push_back(
6205 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRWRResults.getValue(0)));
6206 Results.push_back(CSRWRResults.getValue(1));
6207 break;
6208 }
6209 case Intrinsic::loongarch_csrxchg_w: {
6210 unsigned Imm = N->getConstantOperandVal(4);
6211 if (!isUInt<14>(Imm)) {
6212 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6213 return;
6214 }
6215 SDValue CSRXCHGResults = DAG.getNode(
6216 LoongArchISD::CSRXCHG, DL, {GRLenVT, MVT::Other},
6217 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2),
6218 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)),
6219 DAG.getConstant(Imm, DL, GRLenVT)});
6220 Results.push_back(
6221 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRXCHGResults.getValue(0)));
6222 Results.push_back(CSRXCHGResults.getValue(1));
6223 break;
6224 }
6225#define IOCSRRD_CASE(NAME, NODE) \
6226 case Intrinsic::loongarch_##NAME: { \
6227 SDValue IOCSRRDResults = \
6228 DAG.getNode(LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6229 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2)}); \
6230 Results.push_back( \
6231 DAG.getNode(ISD::TRUNCATE, DL, VT, IOCSRRDResults.getValue(0))); \
6232 Results.push_back(IOCSRRDResults.getValue(1)); \
6233 break; \
6234 }
6235 IOCSRRD_CASE(iocsrrd_b, IOCSRRD_B);
6236 IOCSRRD_CASE(iocsrrd_h, IOCSRRD_H);
6237 IOCSRRD_CASE(iocsrrd_w, IOCSRRD_W);
6238#undef IOCSRRD_CASE
6239 case Intrinsic::loongarch_cpucfg: {
6240 SDValue CPUCFGResults =
6241 DAG.getNode(LoongArchISD::CPUCFG, DL, {GRLenVT, MVT::Other},
6242 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2)});
6243 Results.push_back(
6244 DAG.getNode(ISD::TRUNCATE, DL, VT, CPUCFGResults.getValue(0)));
6245 Results.push_back(CPUCFGResults.getValue(1));
6246 break;
6247 }
6248 case Intrinsic::loongarch_lddir_d: {
6249 if (!Subtarget.is64Bit()) {
6250 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqLA64);
6251 return;
6252 }
6253 break;
6254 }
6255 }
6256 break;
6257 }
6258 case ISD::READ_REGISTER: {
6259 if (Subtarget.is64Bit())
6260 DAG.getContext()->emitError(
6261 "On LA64, only 64-bit registers can be read.");
6262 else
6263 DAG.getContext()->emitError(
6264 "On LA32, only 32-bit registers can be read.");
6265 Results.push_back(DAG.getUNDEF(VT));
6266 Results.push_back(N->getOperand(0));
6267 break;
6268 }
6270 replaceINTRINSIC_WO_CHAINResults(N, Results, DAG, Subtarget);
6271 break;
6272 }
6273 case ISD::LROUND: {
6274 SDValue Op0 = N->getOperand(0);
6275 EVT OpVT = Op0.getValueType();
6276 RTLIB::Libcall LC =
6277 OpVT == MVT::f64 ? RTLIB::LROUND_F64 : RTLIB::LROUND_F32;
6278 MakeLibCallOptions CallOptions;
6279 CallOptions.setTypeListBeforeSoften(OpVT, MVT::i64);
6280 SDValue Result = makeLibCall(DAG, LC, MVT::i64, Op0, CallOptions, DL).first;
6281 Result = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Result);
6282 Results.push_back(Result);
6283 break;
6284 }
6285 case ISD::ATOMIC_CMP_SWAP: {
6287 break;
6288 }
6289 case ISD::TRUNCATE: {
6290 MVT VT = N->getSimpleValueType(0);
6291 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
6292 return;
6293
6294 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
6295 SDValue In = N->getOperand(0);
6296 EVT InVT = In.getValueType();
6297 EVT InEltVT = InVT.getVectorElementType();
6298 EVT EltVT = VT.getVectorElementType();
6299 unsigned MinElts = VT.getVectorNumElements();
6300 unsigned WidenNumElts = WidenVT.getVectorNumElements();
6301 unsigned InBits = InVT.getSizeInBits();
6302
6303 // v8i64 -> (v8i32) -> v8i8
6304 if (InVT == MVT::v8i64 && WidenVT.is128BitVector()) {
6305 InVT = MVT::getVectorVT(MVT::getIntegerVT(256 / MinElts), MinElts);
6306 In = DAG.getNode(N->getOpcode(), DL, InVT, In);
6307 InBits = 256;
6308 }
6309
6310 // v8i32 -> v8i8 / v4i64 -> v4i16 / v4i64 -> v4i8
6311 if ((InVT == MVT::v8i32 || InVT == MVT::v4i64) &&
6312 WidenVT.is128BitVector()) {
6313 InVT = MVT::getVectorVT(MVT::getIntegerVT(128 / MinElts), MinElts);
6314 In = DAG.getNode(N->getOpcode(), DL, InVT, In);
6315 InBits = 128;
6316 InEltVT = InVT.getVectorElementType();
6317 }
6318
6319 if ((128 % InBits) == 0 && WidenVT.is128BitVector()) {
6320 if ((InEltVT.getSizeInBits() % EltVT.getSizeInBits()) == 0) {
6321 int Scale = InEltVT.getSizeInBits() / EltVT.getSizeInBits();
6322 SmallVector<int, 16> TruncMask(WidenNumElts, -1);
6323 for (unsigned I = 0; I < MinElts; ++I)
6324 TruncMask[I] = Scale * I;
6325
6326 unsigned WidenNumElts = 128 / In.getScalarValueSizeInBits();
6327 MVT SVT = In.getSimpleValueType().getScalarType();
6328 MVT VT = MVT::getVectorVT(SVT, WidenNumElts);
6329 SDValue WidenIn =
6330 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), In,
6331 DAG.getVectorIdxConstant(0, DL));
6332 assert(isTypeLegal(WidenVT) && isTypeLegal(WidenIn.getValueType()) &&
6333 "Illegal vector type in truncation");
6334 WidenIn = DAG.getBitcast(WidenVT, WidenIn);
6335 Results.push_back(
6336 DAG.getVectorShuffle(WidenVT, DL, WidenIn, WidenIn, TruncMask));
6337 return;
6338 }
6339 }
6340
6341 break;
6342 }
6343 case ISD::SIGN_EXTEND: {
6344 // LASX has native VEXT2XV_* for sign extension.
6345 if (!Subtarget.hasExtLSX() || Subtarget.hasExtLASX())
6346 return;
6347
6348 EVT DstVT = N->getValueType(0);
6349 SDValue Src = N->getOperand(0);
6350
6351 // The VSLTI + VILVL/VILVH expansion below only supports simple vector
6352 // sources no wider than 128 bits. Fall back to the default legalization
6353 // for anything else, e.g. when the mask of an i24 vector compare is
6354 // sign-extended, the promoted <4 x i24> source is not a simple type.
6355 EVT SrcEVT = Src.getValueType();
6356 if (!SrcEVT.isSimple() || SrcEVT.getSizeInBits() > 128)
6357 return;
6358 MVT SrcVT = SrcEVT.getSimpleVT();
6359
6360 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
6361 unsigned DstEltBits = DstVT.getScalarSizeInBits();
6362 unsigned NumElts = DstVT.getVectorNumElements();
6363
6364 if (!DstVT.isVector() || DstVT.getSizeInBits() <= 128)
6365 return;
6366
6367 // If every source element is all-ones or all-zeros, so is every extended
6368 // element, and interleaving a block with itself extends its low half.
6369 bool IsSignSplat = DAG.ComputeNumSignBits(Src) == SrcEltBits;
6370
6371 // Legalize and extend the src to 128-bit first.
6372 if (SrcVT.getSizeInBits() < 128) {
6373 unsigned WidenSrcElts = 128 / SrcEltBits;
6374 MVT WidenSrcVT = MVT::getVectorVT(SrcVT.getScalarType(), WidenSrcElts);
6375 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WidenSrcVT,
6376 DAG.getUNDEF(WidenSrcVT), Src,
6377 DAG.getVectorIdxConstant(0, DL));
6378 SrcVT = WidenSrcVT;
6379
6380 unsigned FirstStageEltBits = 128 / NumElts;
6381 MVT FirstStageEltVT = MVT::getIntegerVT(FirstStageEltBits);
6382 MVT FirstStageVT = MVT::getVectorVT(FirstStageEltVT, NumElts);
6383 Src = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, FirstStageVT, Src);
6384 SrcVT = FirstStageVT;
6385 SrcEltBits = FirstStageEltBits;
6386 }
6387
6389 Blocks.push_back(Src);
6390
6391 // Sign-extend the src by using VSLLWIL (or VILVL for a sign splat) + VEXTH
6392 // recursively.
6393 while (SrcEltBits < DstEltBits) {
6394 unsigned NextEltBits = SrcEltBits * 2;
6395 MVT NextEltVT = MVT::getIntegerVT(NextEltBits);
6396 unsigned CurEltsPerBlock = SrcVT.getVectorNumElements();
6397 unsigned NextEltsPerBlock = CurEltsPerBlock / 2;
6398 MVT NextBlockVT = MVT::getVectorVT(NextEltVT, NextEltsPerBlock);
6399
6400 SmallVector<SDValue, 8> NextBlocks;
6401 NextBlocks.reserve(Blocks.size() * 2);
6402 for (SDValue Block : Blocks) {
6403 SDValue Lo;
6404 if (IsSignSplat) {
6405 Lo = DAG.getNode(LoongArchISD::VILVL, DL, SrcVT, Block, Block);
6406 Lo = DAG.getBitcast(NextBlockVT, Lo);
6407 } else {
6408 Lo = DAG.getNode(LoongArchISD::VSLLWIL, DL, NextBlockVT, Block,
6409 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
6410 }
6411 NextBlocks.push_back(Lo);
6412 NextBlocks.push_back(
6413 DAG.getNode(LoongArchISD::VEXTH, DL, NextBlockVT, Block));
6414 }
6415
6416 Blocks = std::move(NextBlocks);
6417 SrcVT = NextBlockVT;
6418 SrcEltBits = NextEltBits;
6419 }
6420
6421 Results.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Blocks));
6422 break;
6423 }
6424 case ISD::FP_EXTEND:
6425 // FP_EXTEND may reach here due to the Custom action for v2f32 results, but
6426 // no target-specific lowering is required. Leave it unchanged and rely on
6427 // the default type legalization.
6428 break;
6429 }
6430}
6431
6432/// Try to fold: (and (xor X, -1), Y) -> (vandn X, Y).
6434 SelectionDAG &DAG) {
6435 assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDN");
6436
6437 MVT VT = N->getSimpleValueType(0);
6438 if (!VT.is128BitVector() && !VT.is256BitVector())
6439 return SDValue();
6440
6441 SDValue X, Y;
6442 SDValue N0 = N->getOperand(0);
6443 SDValue N1 = N->getOperand(1);
6444
6445 if (SDValue Not = isNOT(N0, DAG)) {
6446 X = Not;
6447 Y = N1;
6448 } else if (SDValue Not = isNOT(N1, DAG)) {
6449 X = Not;
6450 Y = N0;
6451 } else
6452 return SDValue();
6453
6454 X = DAG.getBitcast(VT, X);
6455 Y = DAG.getBitcast(VT, Y);
6456 return DAG.getNode(LoongArchISD::VANDN, DL, VT, X, Y);
6457}
6458
6459static bool isConstantSplatVector(SDValue N, APInt &SplatValue,
6460 unsigned MinSizeInBits) {
6463
6464 if (!Node)
6465 return false;
6466
6467 APInt SplatUndef;
6468 unsigned SplatBitSize;
6469 bool HasAnyUndefs;
6470
6471 return Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6472 HasAnyUndefs, MinSizeInBits,
6473 /*IsBigEndian=*/false);
6474}
6475
6476static SDValue matchDeinterleaveBuildVector(SDValue N, unsigned &StartIndex) {
6477 auto *BV = dyn_cast<BuildVectorSDNode>(N);
6478 if (!BV)
6479 return SDValue();
6480
6481 SDValue Src;
6482 int Start = -1;
6483
6484 for (unsigned i = 0, NumElts = BV->getNumOperands(); i < NumElts; ++i) {
6485 SDValue Op = BV->getOperand(i);
6486 if (Op.isUndef())
6487 continue;
6488 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6489 return SDValue();
6490
6491 auto *IdxC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6492 if (!IdxC)
6493 return SDValue();
6494
6495 unsigned EltIdx = IdxC->getZExtValue();
6496 if (Start < 0)
6497 Start = (int)EltIdx - (int)(i * 2);
6498 if (Start < 0 || Start > 1 || EltIdx != (unsigned)(Start + (int)(i * 2)))
6499 return SDValue();
6500
6501 SDValue CurSrc = Op.getOperand(0);
6502 if (!Src)
6503 Src = CurSrc;
6504 else if (Src != CurSrc)
6505 return SDValue();
6506 }
6507
6508 if (!Src || Start < 0)
6509 return SDValue();
6510
6511 StartIndex = (unsigned)Start;
6512 return Src;
6513}
6514
6515// Return true if values of type VT are kept in vector registers, i.e. VT is
6516// a vector type whose elements are legal in LSX vectors.
6517static bool isVectorRegisterVT(EVT VT, SelectionDAG &DAG) {
6518 if (!VT.isVector())
6519 return false;
6520 EVT EltVT = VT.getVectorElementType();
6521 unsigned EltBits = EltVT.getSizeInBits();
6522 if (EltBits < 8 || EltBits > 64)
6523 return false;
6524 EVT LSXVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 128 / EltBits);
6525 return DAG.getTargetLoweringInfo().isTypeLegal(LSXVT);
6526}
6527
6528// Return true if all users of the value loaded by Ld can use it in vector
6529// registers.
6531 EVT VT = Ld->getValueType(0);
6532 for (SDUse &U : Ld->uses()) {
6533 if (U.getResNo() != 0)
6534 continue;
6535 SDNode *User = U.getUser();
6536 switch (User->getOpcode()) {
6537 case ISD::ADD:
6538 case ISD::SUB:
6539 if (User->getValueType(0) == VT)
6540 continue;
6541 break;
6542 case ISD::STORE:
6543 // The stored value, not the address.
6544 if (U.getOperandNo() == 1)
6545 continue;
6546 break;
6547 case ISD::BITCAST:
6548 if (isVectorRegisterVT(User->getValueType(0), DAG))
6549 continue;
6550 break;
6551 }
6552 return false;
6553 }
6554 return true;
6555}
6556
6557// Return true if V, a vNi128 value, is cheap to obtain in vector registers
6558// of type PartVT.
6560 SelectionDAG &DAG) {
6561 switch (V.getOpcode()) {
6562 case ISD::LOAD: {
6563 auto *Ld = cast<LoadSDNode>(V);
6564 unsigned Fast = 0;
6565 return ISD::isNormalLoad(Ld) && Ld->isSimple() &&
6567 *DAG.getContext(), DAG.getDataLayout(), PartVT,
6568 *Ld->getMemOperand(), &Fast) &&
6569 Fast && hasOnlyVectorUsers(Ld, DAG);
6570 }
6571 case ISD::BITCAST: {
6572 // Vectors built from GPRs are not in vector registers.
6573 SDValue Src = V.getOperand(0);
6574 switch (Src.getOpcode()) {
6575 case ISD::BUILD_VECTOR:
6579 return false;
6580 }
6581 return isVectorRegisterVT(Src.getValueType(), DAG);
6582 }
6583 default:
6585 }
6586}
6587
6588// Combine add/sub on vNi128 to [X]VADD.Q/[X]VSUB.Q:
6589//
6590// (add vNi128:a, vNi128:b)
6591// -> (bitcast (VADD_Q (bitcast a to vMi64), (bitcast b to vMi64)))
6592//
6593// vNi128 types are not legal and would otherwise be expanded to scalar
6594// add/sub with carry on GPRs, so this has to happen before type legalization.
6595// Vectors wider than a vector register are split into register-sized parts.
6596// Only do it when both operands are already in, or cheap to get into, vector
6597// registers, e.g. loaded from memory. Values passed in GPRs (such as function
6598// arguments) are better handled in GPRs.
6602 if (!Subtarget.hasExtLSX())
6603 return SDValue();
6604 if (!DCI.isBeforeLegalize())
6605 return SDValue();
6606
6607 EVT VT = N->getValueType(0);
6608 if (!VT.isFixedLengthVector() || VT.getVectorElementType() != MVT::i128)
6609 return SDValue();
6610
6611 // Use 256-bit parts with LASX and 128-bit parts for the rest.
6612 unsigned NumElts = VT.getVectorNumElements();
6613 bool UseLASX = Subtarget.hasExtLASX() && NumElts >= 2;
6614 MVT PartVT = UseLASX ? MVT::v4i64 : MVT::v2i64;
6615 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i64, NumElts * 2);
6616
6617 SDValue LHS = N->getOperand(0);
6618 SDValue RHS = N->getOperand(1);
6619 if (!isCheapVNi128VectorOperand(LHS, PartVT, DAG) ||
6620 !isCheapVNi128VectorOperand(RHS, PartVT, DAG))
6621 return SDValue();
6622
6623 // Replace loads with loads of the i64 vector type, so that the other users
6624 // of the loaded value (e.g. another add/sub) can use it directly as well.
6625 // The range metadata, if any, is dropped as it doesn't match the new type.
6626 // The old loads are only replaced after N, as replacing them may CSE N into
6627 // another node and delete it.
6629 auto ConvertOperand = [&](SDValue V) {
6630 auto *Ld = dyn_cast<LoadSDNode>(V);
6631 if (!Ld)
6632 return DAG.getBitcast(NewVT, V);
6633 SDValue NewLd =
6634 DAG.getLoad(NewVT, SDLoc(Ld), Ld->getChain(), Ld->getBasePtr(),
6635 Ld->getPointerInfo(), Ld->getBaseAlign(),
6636 Ld->getMemOperand()->getFlags(), Ld->getAAInfo());
6637 LoadsToReplace.push_back({Ld, NewLd});
6638 return NewLd;
6639 };
6640 SDValue NewLHS = ConvertOperand(LHS);
6641 SDValue NewRHS = LHS == RHS ? NewLHS : ConvertOperand(RHS);
6642
6643 SDLoc DL(N);
6644 unsigned Opc =
6645 N->getOpcode() == ISD::ADD ? LoongArchISD::VADD_Q : LoongArchISD::VSUB_Q;
6646 SDValue Res = DAG.getUNDEF(NewVT);
6647 for (unsigned Idx = 0, End = NumElts * 2; Idx != End;) {
6648 MVT CurVT = UseLASX && End - Idx >= 4 ? MVT::v4i64 : MVT::v2i64;
6649 SDValue PartLHS = DAG.getExtractSubvector(DL, CurVT, NewLHS, Idx);
6650 SDValue PartRHS = DAG.getExtractSubvector(DL, CurVT, NewRHS, Idx);
6651 SDValue Part = DAG.getNode(Opc, DL, CurVT, PartLHS, PartRHS);
6652 Res = DAG.getInsertSubvector(DL, Res, Part, Idx);
6653 Idx += CurVT.getVectorNumElements();
6654 }
6655 DCI.CombineTo(N, DAG.getBitcast(VT, Res));
6656 for (auto [Ld, NewLd] : LoadsToReplace)
6657 DCI.CombineTo(Ld, DAG.getBitcast(VT, NewLd), NewLd.getValue(1));
6658 return SDValue(N, 0);
6659}
6660
6661static SDValue
6664 if (!Subtarget.hasExtLSX())
6665 return SDValue();
6666
6667 unsigned Opc = N->getOpcode();
6668 assert((Opc == ISD::ADD || Opc == ISD::SUB) && "Unexpected opcode");
6669
6670 EVT VT = N->getValueType(0);
6671 SDLoc DL(N);
6672
6673 SDValue LHS = N->getOperand(0);
6674 SDValue RHS = N->getOperand(1);
6675
6676 bool isSigned;
6677 unsigned ExtOpc = LHS.getOpcode();
6678 if (ExtOpc == ISD::SIGN_EXTEND)
6679 isSigned = true;
6680 else if (ExtOpc == ISD::ZERO_EXTEND)
6681 isSigned = false;
6682 else
6683 return SDValue();
6684
6685 if (ExtOpc != RHS.getOpcode())
6686 return SDValue();
6687
6688 if (!LHS.hasOneUse() || !RHS.hasOneUse())
6689 return SDValue();
6690
6691 unsigned OddIdx, EvenIdx;
6692 SDValue LHSVec = matchDeinterleaveBuildVector(LHS.getOperand(0), OddIdx);
6693 SDValue RHSVec = matchDeinterleaveBuildVector(RHS.getOperand(0), EvenIdx);
6694
6695 if (!LHSVec || !RHSVec)
6696 return SDValue();
6697 if (OddIdx != 1 || EvenIdx != 0)
6698 return SDValue();
6699 if (LHSVec.getValueType() != RHSVec.getValueType())
6700 return SDValue();
6701
6702 EVT SrcVT = LHSVec.getValueType();
6703 EVT SrcEltVT = SrcVT.getVectorElementType();
6704 EVT DstEltVT = VT.getVectorElementType();
6705 auto &TLI = DAG.getTargetLoweringInfo();
6706
6707 if (!TLI.isTypeLegal(VT) || !TLI.isTypeLegal(SrcVT))
6708 return SDValue();
6709 if (!SrcVT.isVector() || !VT.isVector())
6710 return SDValue();
6711 if (SrcVT.getSizeInBits() != VT.getSizeInBits())
6712 return SDValue();
6713 if (DstEltVT.getSizeInBits() != SrcEltVT.getSizeInBits() * 2)
6714 return SDValue();
6715 if (!SrcEltVT.isInteger() || SrcEltVT.getSizeInBits() > 32)
6716 return SDValue();
6717
6718 unsigned TargetOpc;
6719 if (Opc == ISD::ADD)
6720 TargetOpc = isSigned ? LoongArchISD::VHADDW : LoongArchISD::VHADDW_U;
6721 else
6722 TargetOpc = isSigned ? LoongArchISD::VHSUBW : LoongArchISD::VHSUBW_U;
6723
6724 return DAG.getNode(TargetOpc, DL, VT, LHSVec, RHSVec);
6725}
6726
6731 return V;
6732
6734 return V;
6735
6736 if (DCI.isBeforeLegalizeOps())
6737 return SDValue();
6738
6739 EVT VT = N->getValueType(0);
6740 if (!VT.isVector())
6741 return SDValue();
6742
6743 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6744 return SDValue();
6745
6746 EVT EltVT = VT.getVectorElementType();
6747 if (!EltVT.isInteger())
6748 return SDValue();
6749
6750 // match:
6751 //
6752 // add
6753 // (and
6754 // (srl X, shift-1) / X
6755 // 1)
6756 // (srl/sra X, shift)
6757
6758 SDValue Add0 = N->getOperand(0);
6759 SDValue Add1 = N->getOperand(1);
6760 SDValue And;
6761 SDValue Shr;
6762
6763 if (Add0.getOpcode() == ISD::AND) {
6764 And = Add0;
6765 Shr = Add1;
6766 } else if (Add1.getOpcode() == ISD::AND) {
6767 And = Add1;
6768 Shr = Add0;
6769 } else {
6770 return SDValue();
6771 }
6772
6773 // match:
6774 //
6775 // srl/sra X, shift
6776
6777 if (Shr.getOpcode() != ISD::SRL && Shr.getOpcode() != ISD::SRA)
6778 return SDValue();
6779
6780 SDValue X = Shr.getOperand(0);
6781 SDValue Shift = Shr.getOperand(1);
6782 APInt ShiftVal;
6783
6784 if (!isConstantSplatVector(Shift, ShiftVal, EltVT.getSizeInBits()))
6785 return SDValue();
6786
6787 if (ShiftVal == 0)
6788 return SDValue();
6789
6790 // match:
6791 //
6792 // and
6793 // (srl X, shift-1) / X
6794 // 1
6795
6796 SDValue One = And.getOperand(1);
6797 APInt SplatVal;
6798
6799 if (!isConstantSplatVector(One, SplatVal, EltVT.getSizeInBits()))
6800 return SDValue();
6801
6802 if (SplatVal != 1)
6803 return SDValue();
6804
6805 if (And.getOperand(0) == X) {
6806 // match:
6807 //
6808 // shift == 1
6809
6810 if (ShiftVal != 1)
6811 return SDValue();
6812 } else {
6813 // match:
6814 //
6815 // srl X, shift-1
6816
6817 SDValue Srl = And.getOperand(0);
6818
6819 if (Srl.getOpcode() != ISD::SRL)
6820 return SDValue();
6821
6822 if (Srl.getOperand(0) != X)
6823 return SDValue();
6824
6825 // match:
6826 //
6827 // shift-1
6828
6829 SDValue ShiftMinus1 = Srl.getOperand(1);
6830
6831 if (!isConstantSplatVector(ShiftMinus1, SplatVal, EltVT.getSizeInBits()))
6832 return SDValue();
6833
6834 if (ShiftVal != (SplatVal + 1))
6835 return SDValue();
6836 }
6837
6838 // We matched a rounded right shift pattern and can lower it
6839 // to a single vector rounded shift instruction.
6840
6841 SDLoc DL(N);
6842 return DAG.getNode(Shr.getOpcode() == ISD::SRL ? LoongArchISD::VSRLR
6843 : LoongArchISD::VSRAR,
6844 DL, VT, X, Shift);
6845}
6846
6850 if (DCI.isBeforeLegalizeOps())
6851 return SDValue();
6852
6853 SDValue FirstOperand = N->getOperand(0);
6854 SDValue SecondOperand = N->getOperand(1);
6855 unsigned FirstOperandOpc = FirstOperand.getOpcode();
6856 EVT ValTy = N->getValueType(0);
6857 SDLoc DL(N);
6858 uint64_t lsb, msb;
6859 unsigned SMIdx, SMLen;
6860 ConstantSDNode *CN;
6861 SDValue NewOperand;
6862 MVT GRLenVT = Subtarget.getGRLenVT();
6863
6864 if (SDValue R = combineAndNotIntoVANDN(N, DL, DAG))
6865 return R;
6866
6867 // BSTRPICK requires the 32S feature.
6868 if (!Subtarget.has32S())
6869 return SDValue();
6870
6871 // Op's second operand must be a shifted mask.
6872 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)) ||
6873 !isShiftedMask_64(CN->getZExtValue(), SMIdx, SMLen))
6874 return SDValue();
6875
6876 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
6877 // Pattern match BSTRPICK.
6878 // $dst = and ((sra or srl) $src , lsb), (2**len - 1)
6879 // => BSTRPICK $dst, $src, msb, lsb
6880 // where msb = lsb + len - 1
6881
6882 // The second operand of the shift must be an immediate.
6883 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
6884 return SDValue();
6885
6886 lsb = CN->getZExtValue();
6887
6888 // Return if the shifted mask does not start at bit 0 or the sum of its
6889 // length and lsb exceeds the word's size.
6890 if (SMIdx != 0 || lsb + SMLen > ValTy.getSizeInBits())
6891 return SDValue();
6892
6893 NewOperand = FirstOperand.getOperand(0);
6894 } else {
6895 // Pattern match BSTRPICK.
6896 // $dst = and $src, (2**len- 1) , if len > 12
6897 // => BSTRPICK $dst, $src, msb, lsb
6898 // where lsb = 0 and msb = len - 1
6899
6900 // If the mask is <= 0xfff, andi can be used instead.
6901 if (CN->getZExtValue() <= 0xfff)
6902 return SDValue();
6903
6904 // Return if the MSB exceeds.
6905 if (SMIdx + SMLen > ValTy.getSizeInBits())
6906 return SDValue();
6907
6908 if (SMIdx > 0) {
6909 // Omit if the constant has more than 2 uses. This a conservative
6910 // decision. Whether it is a win depends on the HW microarchitecture.
6911 // However it should always be better for 1 and 2 uses.
6912 if (CN->use_size() > 2)
6913 return SDValue();
6914 // Return if the constant can be composed by a single LU12I.W.
6915 if ((CN->getZExtValue() & 0xfff) == 0)
6916 return SDValue();
6917 // Return if the constand can be composed by a single ADDI with
6918 // the zero register.
6919 if (CN->getSExtValue() >= -2048 && CN->getSExtValue() < 0)
6920 return SDValue();
6921 }
6922
6923 lsb = SMIdx;
6924 NewOperand = FirstOperand;
6925 }
6926
6927 msb = lsb + SMLen - 1;
6928 SDValue NR0 = DAG.getNode(LoongArchISD::BSTRPICK, DL, ValTy, NewOperand,
6929 DAG.getConstant(msb, DL, GRLenVT),
6930 DAG.getConstant(lsb, DL, GRLenVT));
6931 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL || lsb == 0)
6932 return NR0;
6933 // Try to optimize to
6934 // bstrpick $Rd, $Rs, msb, lsb
6935 // slli $Rd, $Rd, lsb
6936 return DAG.getNode(ISD::SHL, DL, ValTy, NR0,
6937 DAG.getConstant(lsb, DL, GRLenVT));
6938}
6939
6940// Return the original source vector if N consists of the half
6941// of each 128-bit lane.
6944
6945 EVT DstVT = N.getValueType();
6946 if (!DstVT.isVector())
6947 return SDValue();
6948
6949 unsigned NumElts = DstVT.getVectorNumElements();
6950
6951 // LSX canonical form:
6952 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6953 SDValue Src = N.getOperand(0);
6954 EVT SrcVT = Src.getValueType();
6955
6956 if (!SrcVT.isVector() || !SrcVT.is128BitVector())
6957 return SDValue();
6958 if (SrcVT.getSizeInBits() != DstVT.getSizeInBits() * 2)
6959 return SDValue();
6960 if (SrcVT.getVectorNumElements() != NumElts * 2)
6961 return SDValue();
6962 if (N.getConstantOperandVal(1) != (isLow ? 0 : NumElts))
6963 return SDValue();
6964
6965 return Src;
6966 }
6967
6968 // LASX canonical form:
6969 auto *BV = dyn_cast<BuildVectorSDNode>(N);
6970 if (!BV)
6971 return SDValue();
6972
6973 if (NumElts % 2 != 0)
6974 return SDValue();
6975
6976 SDValue Src;
6977 EVT SrcVT;
6978
6979 for (unsigned I = 0; I != NumElts; ++I) {
6980 SDValue Elt = BV->getOperand(I);
6981 if (Elt.isUndef())
6982 continue;
6984 return SDValue();
6985
6986 SDValue ThisSrc = Elt.getOperand(0);
6987 SDValue Idx = Elt.getOperand(1);
6988 auto *CI = dyn_cast<ConstantSDNode>(Idx);
6989 if (!CI)
6990 return SDValue();
6991
6992 if (!Src) {
6993 Src = ThisSrc;
6994 SrcVT = Src.getValueType();
6995 if (!SrcVT.isVector())
6996 return SDValue();
6997
6998 if (!SrcVT.is256BitVector())
6999 return SDValue();
7000 if (SrcVT.getSizeInBits() != DstVT.getSizeInBits() * 2)
7001 return SDValue();
7002 if (SrcVT.getVectorNumElements() != NumElts * 2)
7003 return SDValue();
7004 } else if (ThisSrc != Src) {
7005 return SDValue();
7006 }
7007
7008 unsigned Half = NumElts / 2;
7009 unsigned ExpectedIdx = (I < Half) ? I : (I + Half);
7010 ExpectedIdx += isLow ? 0 : Half;
7011
7012 if (CI->getZExtValue() != ExpectedIdx)
7013 return SDValue();
7014 }
7015
7016 return Src;
7017}
7018
7022 assert(N->getOpcode() == ISD::SHL && "Unexpected opcode");
7023
7024 EVT VT = N->getValueType(0);
7025 SDLoc DL(N);
7026
7027 SDValue LHS = N->getOperand(0);
7028 SDValue RHS = N->getOperand(1);
7029
7030 bool isSigned;
7031 unsigned ExtOpc = LHS.getOpcode();
7032 if (ExtOpc == ISD::SIGN_EXTEND)
7033 isSigned = true;
7034 else if (ExtOpc == ISD::ZERO_EXTEND)
7035 isSigned = false;
7036 else
7037 return SDValue();
7038
7039 if (!LHS.hasOneUse())
7040 return SDValue();
7041
7042 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) ||
7043 N->getValueSizeInBits(0) != LHS->getOperand(0).getValueSizeInBits() * 2)
7044 return SDValue();
7045
7046 SDValue Vec = matchHalfOf128BitLanes(LHS.getOperand(0), /*isLow=*/true);
7047 if (!Vec)
7048 return SDValue();
7049
7050 EVT SrcVT = Vec.getValueType();
7051 EVT SrcEltVT = SrcVT.getVectorElementType();
7052 EVT DstEltVT = VT.getVectorElementType();
7053 APInt Imm;
7054 if (!isConstantSplatVector(RHS, Imm, DstEltVT.getSizeInBits()))
7055 return SDValue();
7056 if (!Imm.ult(SrcEltVT.getSizeInBits()))
7057 return SDValue();
7058
7059 unsigned Opc = isSigned ? LoongArchISD::VSLLWIL : LoongArchISD::VSLLWIL_U;
7060 SDValue Sht = DAG.getConstant(Imm.getZExtValue(), DL, Subtarget.getGRLenVT());
7061 return DAG.getNode(Opc, DL, VT, Vec, Sht);
7062}
7063
7067 // BSTRPICK requires the 32S feature.
7068 if (!Subtarget.has32S())
7069 return SDValue();
7070
7071 if (DCI.isBeforeLegalizeOps())
7072 return SDValue();
7073
7074 // $dst = srl (and $src, Mask), Shamt
7075 // =>
7076 // BSTRPICK $dst, $src, MaskIdx+MaskLen-1, Shamt
7077 // when Mask is a shifted mask, and MaskIdx <= Shamt <= MaskIdx+MaskLen-1
7078 //
7079
7080 SDValue FirstOperand = N->getOperand(0);
7081 ConstantSDNode *CN;
7082 EVT ValTy = N->getValueType(0);
7083 SDLoc DL(N);
7084 MVT GRLenVT = Subtarget.getGRLenVT();
7085 unsigned MaskIdx, MaskLen;
7086 uint64_t Shamt;
7087
7088 // The first operand must be an AND and the second operand of the AND must be
7089 // a shifted mask.
7090 if (FirstOperand.getOpcode() != ISD::AND ||
7091 !(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
7092 !isShiftedMask_64(CN->getZExtValue(), MaskIdx, MaskLen))
7093 return SDValue();
7094
7095 // The second operand (shift amount) must be an immediate.
7096 if (!(CN = dyn_cast<ConstantSDNode>(N->getOperand(1))))
7097 return SDValue();
7098
7099 Shamt = CN->getZExtValue();
7100 if (MaskIdx <= Shamt && Shamt <= MaskIdx + MaskLen - 1)
7101 return DAG.getNode(LoongArchISD::BSTRPICK, DL, ValTy,
7102 FirstOperand->getOperand(0),
7103 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7104 DAG.getConstant(Shamt, DL, GRLenVT));
7105
7106 return SDValue();
7107}
7108
7109// Try to turn a sub boolean RHS and constant LHS into an addi. LoongArch's
7110// SUB has no immediate form, so (sub C, X) normally requires either
7111// materializing C or using sub with R0 plus an addi; rewriting it as
7112// (add X', C - 1) lets the immediate fold into a single ADDI.
7114 SDValue N0 = N->getOperand(0);
7115 SDValue N1 = N->getOperand(1);
7116 EVT VT = N->getValueType(0);
7117 SDLoc DL(N);
7118
7119 // Require a constant LHS.
7120 auto *N0C = dyn_cast<ConstantSDNode>(N0);
7121 if (!N0C)
7122 return SDValue();
7123
7124 // (sub 0, X) is a negation, not a constant materialization; rewriting it
7125 // as (add (setcc inv), -1) changes the condition code and can duplicate a
7126 // compare, without saving any instruction.
7127 if (N0C->isZero() && !N->hasOneUse())
7128 return SDValue();
7129
7130 // The result of this fold is only folded into an ADDI when it is used
7131 // directly. When it feeds an extend, the original (sub C, X) form usually
7132 // combines better with the surrounding zext/negate/xor.
7133 if (N->hasOneUse()) {
7134 unsigned UserOpc = N->use_begin()->getUser()->getOpcode();
7135 if (UserOpc == ISD::ZERO_EXTEND || UserOpc == ISD::SIGN_EXTEND ||
7136 UserOpc == ISD::ANY_EXTEND || UserOpc == ISD::SUB)
7137 return SDValue();
7138 }
7139
7140 // All our optimizations involve subtracting 1 from the immediate and
7141 // forming an ADDI. Make sure the new immediate is valid for an ADDI.
7142 APInt ImmValMinus1 = N0C->getAPIntValue() - 1;
7143 if (!ImmValMinus1.isSignedIntN(12))
7144 return SDValue();
7145
7146 SDValue NewLHS;
7147 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse()) {
7148 // (sub constant, (setcc x, y, eq/neq)) ->
7149 // (add (setcc x, y, neq/eq), constant - 1)
7150 ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get();
7151 EVT SetCCOpVT = N1.getOperand(0).getValueType();
7152 if (!ISD::isIntEqualitySetCC(CCVal) || !SetCCOpVT.isInteger())
7153 return SDValue();
7154 CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT);
7155 NewLHS =
7156 DAG.getSetCC(SDLoc(N1), VT, N1.getOperand(0), N1.getOperand(1), CCVal);
7157 } else if (N1.getOpcode() == ISD::XOR && isOneConstant(N1.getOperand(1)) &&
7158 N1.getOperand(0).getOpcode() == ISD::SETCC) {
7159 // (sub C, (xor (setcc), 1)) -> (add (setcc), C-1).
7160 // Since setcc returns a bool the xor is equivalent to 1-setcc.
7161 NewLHS = N1.getOperand(0);
7162 } else
7163 return SDValue();
7164
7165 SDValue NewRHS = DAG.getConstant(ImmValMinus1, DL, VT);
7166 return DAG.getNode(ISD::ADD, DL, VT, NewLHS, NewRHS);
7167}
7168
7173 return V;
7174
7176 return V;
7177
7178 if (N->getValueType(0) != Subtarget.getGRLenVT())
7179 return SDValue();
7180
7181 SDValue N0 = N->getOperand(0);
7182 SDValue N1 = N->getOperand(1);
7183 EVT VT = N->getValueType(0);
7184
7185 if (SDValue V = combineSubOfBoolean(N, DAG))
7186 return V;
7187
7188 // fold (sub 0, (setcc x, 0, setlt)) -> (sra x, xlen - 1)
7189 if (isNullConstant(N0) && N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
7190 isNullConstant(N1.getOperand(1)) &&
7191 N1.getValueType() == N1.getOperand(0).getValueType()) {
7192 ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get();
7193 if (CCVal == ISD::SETLT) {
7194 SDLoc DL(N);
7195 unsigned ShAmt = N0.getValueSizeInBits() - 1;
7196 return DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0),
7197 DAG.getConstant(ShAmt, DL, VT));
7198 }
7199 }
7200
7201 return SDValue();
7202}
7203
7204// Helper to peek through bitops/trunc/setcc to determine size of source vector.
7205// Allows BITCASTCombine to determine what size vector generated a <X x i1>.
7206static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
7207 unsigned Depth) {
7208 // Limit recursion.
7210 return false;
7211 switch (Src.getOpcode()) {
7212 case ISD::SETCC:
7213 case ISD::TRUNCATE:
7214 return Src.getOperand(0).getValueSizeInBits() == Size;
7215 case ISD::FREEZE:
7216 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, Depth + 1);
7217 case ISD::AND:
7218 case ISD::XOR:
7219 case ISD::OR:
7220 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, Depth + 1) &&
7221 checkBitcastSrcVectorSize(Src.getOperand(1), Size, Depth + 1);
7222 case ISD::SELECT:
7223 case ISD::VSELECT:
7224 return Src.getOperand(0).getScalarValueSizeInBits() == 1 &&
7225 checkBitcastSrcVectorSize(Src.getOperand(1), Size, Depth + 1) &&
7226 checkBitcastSrcVectorSize(Src.getOperand(2), Size, Depth + 1);
7227 case ISD::BUILD_VECTOR:
7229 }
7230 return false;
7231}
7232
7233// Helper to push sign extension of vXi1 SETCC result through bitops.
7235 SDValue Src, const SDLoc &DL) {
7236 switch (Src.getOpcode()) {
7237 case ISD::SETCC:
7238 case ISD::FREEZE:
7239 case ISD::TRUNCATE:
7240 case ISD::BUILD_VECTOR:
7241 return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
7242 case ISD::AND:
7243 case ISD::XOR:
7244 case ISD::OR:
7245 return DAG.getNode(
7246 Src.getOpcode(), DL, SExtVT,
7247 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
7248 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
7249 case ISD::SELECT:
7250 case ISD::VSELECT:
7251 return DAG.getSelect(
7252 DL, SExtVT, Src.getOperand(0),
7253 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL),
7254 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(2), DL));
7255 }
7256 llvm_unreachable("Unexpected node type for vXi1 sign extension");
7257}
7258
7259static SDValue
7263 SDLoc DL(N);
7264 EVT VT = N->getValueType(0);
7265 SDValue Src = N->getOperand(0);
7266 EVT SrcVT = Src.getValueType();
7267
7268 if (Src.getOpcode() != ISD::SETCC || !Src.hasOneUse())
7269 return SDValue();
7270
7271 bool UseLASX;
7272 unsigned Opc = ISD::DELETED_NODE;
7273 EVT CmpVT = Src.getOperand(0).getValueType();
7274 EVT EltVT = CmpVT.getVectorElementType();
7275
7276 if (Subtarget.hasExtLSX() && CmpVT.getSizeInBits() == 128)
7277 UseLASX = false;
7278 else if (Subtarget.has32S() && Subtarget.hasExtLASX() &&
7279 CmpVT.getSizeInBits() == 256)
7280 UseLASX = true;
7281 else
7282 return SDValue();
7283
7284 SDValue SrcN1 = Src.getOperand(1);
7285 switch (Src.getOperandCondCode(2)) {
7286 default:
7287 break;
7288 case ISD::SETEQ:
7289 // x == 0 => not (vmsknez.b x)
7290 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7291 Opc = UseLASX ? LoongArchISD::XVMSKEQZ : LoongArchISD::VMSKEQZ;
7292 break;
7293 case ISD::SETGT:
7294 // x > -1 => vmskgez.b x
7295 if (ISD::isBuildVectorAllOnes(SrcN1) && EltVT == MVT::i8)
7296 Opc = UseLASX ? LoongArchISD::XVMSKGEZ : LoongArchISD::VMSKGEZ;
7297 break;
7298 case ISD::SETGE:
7299 // x >= 0 => vmskgez.b x
7300 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7301 Opc = UseLASX ? LoongArchISD::XVMSKGEZ : LoongArchISD::VMSKGEZ;
7302 break;
7303 case ISD::SETLT:
7304 // x < 0 => vmskltz.{b,h,w,d} x
7305 if (ISD::isBuildVectorAllZeros(SrcN1) &&
7306 (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
7307 EltVT == MVT::i64))
7308 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7309 break;
7310 case ISD::SETLE:
7311 // x <= -1 => vmskltz.{b,h,w,d} x
7312 if (ISD::isBuildVectorAllOnes(SrcN1) &&
7313 (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
7314 EltVT == MVT::i64))
7315 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7316 break;
7317 case ISD::SETNE:
7318 // x != 0 => vmsknez.b x
7319 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7320 Opc = UseLASX ? LoongArchISD::XVMSKNEZ : LoongArchISD::VMSKNEZ;
7321 break;
7322 }
7323
7324 if (Opc == ISD::DELETED_NODE)
7325 return SDValue();
7326
7327 SDValue V = DAG.getNode(Opc, DL, Subtarget.getGRLenVT(), Src.getOperand(0));
7329 V = DAG.getZExtOrTrunc(V, DL, T);
7330 return DAG.getBitcast(VT, V);
7331}
7332
7336 SDLoc DL(N);
7337 EVT VT = N->getValueType(0);
7338 SDValue Src = N->getOperand(0);
7339 EVT SrcVT = Src.getValueType();
7340 MVT GRLenVT = Subtarget.getGRLenVT();
7341
7342 if (!DCI.isBeforeLegalizeOps())
7343 return SDValue();
7344
7345 if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
7346 return SDValue();
7347
7348 // Combine SETCC and BITCAST into [X]VMSK{LT,GE,NE} when possible
7350 if (Res)
7351 return Res;
7352
7353 // Generate vXi1 using [X]VMSKLTZ
7354 MVT SExtVT;
7355 unsigned Opc;
7356 bool UseLASX = false;
7357 bool PropagateSExt = false;
7358
7359 if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse()) {
7360 EVT CmpVT = Src.getOperand(0).getValueType();
7361 if (CmpVT.getSizeInBits() > 256)
7362 return SDValue();
7363 }
7364
7365 switch (SrcVT.getSimpleVT().SimpleTy) {
7366 default:
7367 return SDValue();
7368 case MVT::v2i1:
7369 SExtVT = MVT::v2i64;
7370 break;
7371 case MVT::v4i1:
7372 SExtVT = MVT::v4i32;
7373 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7374 SExtVT = MVT::v4i64;
7375 UseLASX = true;
7376 PropagateSExt = true;
7377 }
7378 break;
7379 case MVT::v8i1:
7380 SExtVT = MVT::v8i16;
7381 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7382 SExtVT = MVT::v8i32;
7383 UseLASX = true;
7384 PropagateSExt = true;
7385 }
7386 break;
7387 case MVT::v16i1:
7388 SExtVT = MVT::v16i8;
7389 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7390 SExtVT = MVT::v16i16;
7391 UseLASX = true;
7392 PropagateSExt = true;
7393 }
7394 break;
7395 case MVT::v32i1:
7396 SExtVT = MVT::v32i8;
7397 UseLASX = true;
7398 break;
7399 };
7400 Src = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
7401 : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
7402
7403 SDValue V;
7404 if (!Subtarget.has32S() || !Subtarget.hasExtLASX()) {
7405 if (Src.getSimpleValueType() == MVT::v32i8) {
7406 SDValue Lo, Hi;
7407 std::tie(Lo, Hi) = DAG.SplitVector(Src, DL);
7408 Lo = DAG.getNode(LoongArchISD::VMSKLTZ, DL, GRLenVT, Lo);
7409 Hi = DAG.getNode(LoongArchISD::VMSKLTZ, DL, GRLenVT, Hi);
7410 Hi = DAG.getNode(ISD::SHL, DL, GRLenVT, Hi,
7411 DAG.getShiftAmountConstant(16, GRLenVT, DL));
7412 V = DAG.getNode(ISD::OR, DL, GRLenVT, Lo, Hi);
7413 } else if (UseLASX) {
7414 return SDValue();
7415 }
7416 }
7417
7418 if (!V) {
7419 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7420 V = DAG.getNode(Opc, DL, GRLenVT, Src);
7421 }
7422
7424 V = DAG.getZExtOrTrunc(V, DL, T);
7425 return DAG.getBitcast(VT, V);
7426}
7427
7431 MVT GRLenVT = Subtarget.getGRLenVT();
7432 EVT ValTy = N->getValueType(0);
7433 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7434 ConstantSDNode *CN0, *CN1;
7435 SDLoc DL(N);
7436 unsigned ValBits = ValTy.getSizeInBits();
7437 unsigned MaskIdx0, MaskLen0, MaskIdx1, MaskLen1;
7438 unsigned Shamt;
7439 bool SwapAndRetried = false;
7440
7441 // BSTRPICK requires the 32S feature.
7442 if (!Subtarget.has32S())
7443 return SDValue();
7444
7445 if (DCI.isBeforeLegalizeOps())
7446 return SDValue();
7447
7448 if (ValBits != 32 && ValBits != 64)
7449 return SDValue();
7450
7451Retry:
7452 // 1st pattern to match BSTRINS:
7453 // R = or (and X, mask0), (and (shl Y, lsb), mask1)
7454 // where mask1 = (2**size - 1) << lsb, mask0 = ~mask1
7455 // =>
7456 // R = BSTRINS X, Y, msb, lsb (where msb = lsb + size - 1)
7457 if (N0.getOpcode() == ISD::AND &&
7458 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7459 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7460 N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL &&
7461 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7462 isShiftedMask_64(CN1->getZExtValue(), MaskIdx1, MaskLen1) &&
7463 MaskIdx0 == MaskIdx1 && MaskLen0 == MaskLen1 &&
7464 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7465 (Shamt = CN1->getZExtValue()) == MaskIdx0 &&
7466 (MaskIdx0 + MaskLen0 <= ValBits)) {
7467 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 1\n");
7468 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7469 N1.getOperand(0).getOperand(0),
7470 DAG.getConstant((MaskIdx0 + MaskLen0 - 1), DL, GRLenVT),
7471 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7472 }
7473
7474 // 2nd pattern to match BSTRINS:
7475 // R = or (and X, mask0), (shl (and Y, mask1), lsb)
7476 // where mask1 = (2**size - 1), mask0 = ~(mask1 << lsb)
7477 // =>
7478 // R = BSTRINS X, Y, msb, lsb (where msb = lsb + size - 1)
7479 if (N0.getOpcode() == ISD::AND &&
7480 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7481 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7482 N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::AND &&
7483 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7484 (Shamt = CN1->getZExtValue()) == MaskIdx0 &&
7485 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7486 isShiftedMask_64(CN1->getZExtValue(), MaskIdx1, MaskLen1) &&
7487 MaskLen0 == MaskLen1 && MaskIdx1 == 0 &&
7488 (MaskIdx0 + MaskLen0 <= ValBits)) {
7489 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 2\n");
7490 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7491 N1.getOperand(0).getOperand(0),
7492 DAG.getConstant((MaskIdx0 + MaskLen0 - 1), DL, GRLenVT),
7493 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7494 }
7495
7496 // 3rd pattern to match BSTRINS:
7497 // R = or (and X, mask0), (and Y, mask1)
7498 // where ~mask0 = (2**size - 1) << lsb, mask0 & mask1 = 0
7499 // =>
7500 // R = BSTRINS X, (shr (and Y, mask1), lsb), msb, lsb
7501 // where msb = lsb + size - 1
7502 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
7503 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7504 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7505 (MaskIdx0 + MaskLen0 <= 64) &&
7506 (CN1 = dyn_cast<ConstantSDNode>(N1->getOperand(1))) &&
7507 (CN1->getSExtValue() & CN0->getSExtValue()) == 0) {
7508 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 3\n");
7509 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7510 DAG.getNode(ISD::SRL, DL, N1->getValueType(0), N1,
7511 DAG.getConstant(MaskIdx0, DL, GRLenVT)),
7512 DAG.getConstant(ValBits == 32
7513 ? (MaskIdx0 + (MaskLen0 & 31) - 1)
7514 : (MaskIdx0 + MaskLen0 - 1),
7515 DL, GRLenVT),
7516 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7517 }
7518
7519 // 4th pattern to match BSTRINS:
7520 // R = or (and X, mask), (shl Y, shamt)
7521 // where mask = (2**shamt - 1)
7522 // =>
7523 // R = BSTRINS X, Y, ValBits - 1, shamt
7524 // where ValBits = 32 or 64
7525 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::SHL &&
7526 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7527 isShiftedMask_64(CN0->getZExtValue(), MaskIdx0, MaskLen0) &&
7528 MaskIdx0 == 0 && (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7529 (Shamt = CN1->getZExtValue()) == MaskLen0 &&
7530 (MaskIdx0 + MaskLen0 <= ValBits)) {
7531 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 4\n");
7532 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7533 N1.getOperand(0),
7534 DAG.getConstant((ValBits - 1), DL, GRLenVT),
7535 DAG.getConstant(Shamt, DL, GRLenVT));
7536 }
7537
7538 // 5th pattern to match BSTRINS:
7539 // R = or (and X, mask), const
7540 // where ~mask = (2**size - 1) << lsb, mask & const = 0
7541 // =>
7542 // R = BSTRINS X, (const >> lsb), msb, lsb
7543 // where msb = lsb + size - 1
7544 if (N0.getOpcode() == ISD::AND &&
7545 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7546 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7547 (CN1 = dyn_cast<ConstantSDNode>(N1)) &&
7548 (CN1->getSExtValue() & CN0->getSExtValue()) == 0) {
7549 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 5\n");
7550 return DAG.getNode(
7551 LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7552 DAG.getSignedConstant(CN1->getSExtValue() >> MaskIdx0, DL, ValTy),
7553 DAG.getConstant(ValBits == 32 ? (MaskIdx0 + (MaskLen0 & 31) - 1)
7554 : (MaskIdx0 + MaskLen0 - 1),
7555 DL, GRLenVT),
7556 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7557 }
7558
7559 // 6th pattern.
7560 // a = b | ((c & mask) << shamt), where all positions in b to be overwritten
7561 // by the incoming bits are known to be zero.
7562 // =>
7563 // a = BSTRINS b, c, shamt + MaskLen - 1, shamt
7564 //
7565 // Note that the 1st pattern is a special situation of the 6th, i.e. the 6th
7566 // pattern is more common than the 1st. So we put the 1st before the 6th in
7567 // order to match as many nodes as possible.
7568 ConstantSDNode *CNMask, *CNShamt;
7569 unsigned MaskIdx, MaskLen;
7570 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::AND &&
7571 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7572 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen) &&
7573 MaskIdx == 0 && (CNShamt = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7574 CNShamt->getZExtValue() + MaskLen <= ValBits) {
7575 Shamt = CNShamt->getZExtValue();
7576 APInt ShMask(ValBits, CNMask->getZExtValue() << Shamt);
7577 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7578 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 6\n");
7579 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7580 N1.getOperand(0).getOperand(0),
7581 DAG.getConstant(Shamt + MaskLen - 1, DL, GRLenVT),
7582 DAG.getConstant(Shamt, DL, GRLenVT));
7583 }
7584 }
7585
7586 // 7th pattern.
7587 // a = b | ((c << shamt) & shifted_mask), where all positions in b to be
7588 // overwritten by the incoming bits are known to be zero.
7589 // =>
7590 // a = BSTRINS b, c, MaskIdx + MaskLen - 1, MaskIdx
7591 //
7592 // Similarly, the 7th pattern is more common than the 2nd. So we put the 2nd
7593 // before the 7th in order to match as many nodes as possible.
7594 if (N1.getOpcode() == ISD::AND &&
7595 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7596 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen) &&
7597 N1.getOperand(0).getOpcode() == ISD::SHL &&
7598 (CNShamt = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7599 CNShamt->getZExtValue() == MaskIdx) {
7600 APInt ShMask(ValBits, CNMask->getZExtValue());
7601 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7602 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 7\n");
7603 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7604 N1.getOperand(0).getOperand(0),
7605 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7606 DAG.getConstant(MaskIdx, DL, GRLenVT));
7607 }
7608 }
7609
7610 // (or a, b) and (or b, a) are equivalent, so swap the operands and retry.
7611 if (!SwapAndRetried) {
7612 std::swap(N0, N1);
7613 SwapAndRetried = true;
7614 goto Retry;
7615 }
7616
7617 SwapAndRetried = false;
7618Retry2:
7619 // 8th pattern.
7620 // a = b | (c & shifted_mask), where all positions in b to be overwritten by
7621 // the incoming bits are known to be zero.
7622 // =>
7623 // a = BSTRINS b, c >> MaskIdx, MaskIdx + MaskLen - 1, MaskIdx
7624 //
7625 // Similarly, the 8th pattern is more common than the 4th and 5th patterns. So
7626 // we put it here in order to match as many nodes as possible or generate less
7627 // instructions.
7628 if (N1.getOpcode() == ISD::AND &&
7629 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7630 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen)) {
7631 APInt ShMask(ValBits, CNMask->getZExtValue());
7632 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7633 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 8\n");
7634 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7635 DAG.getNode(ISD::SRL, DL, N1->getValueType(0),
7636 N1->getOperand(0),
7637 DAG.getConstant(MaskIdx, DL, GRLenVT)),
7638 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7639 DAG.getConstant(MaskIdx, DL, GRLenVT));
7640 }
7641 }
7642 // Swap N0/N1 and retry.
7643 if (!SwapAndRetried) {
7644 std::swap(N0, N1);
7645 SwapAndRetried = true;
7646 goto Retry2;
7647 }
7648
7649 return SDValue();
7650}
7651
7654 EVT VT = N->getValueType(0);
7655 // LA64 promotes i32 integer operations to GPR-width operations during
7656 // legalization. Match the idiom before that promotion as well as after
7657 // it, otherwise common unsigned 32-bit bit tests miss this combine.
7658 if (VT != Subtarget.getGRLenVT() && !(Subtarget.is64Bit() && VT == MVT::i32))
7659 return SDValue();
7660
7661 SDValue XorOps[] = {N->getOperand(0), N->getOperand(1)};
7662 for (unsigned AndIdx = 0; AndIdx != 2; ++AndIdx) {
7663 SDValue And = XorOps[AndIdx];
7664 SDValue Mask = XorOps[1 - AndIdx];
7665 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
7666 continue;
7667
7668 for (unsigned MaskIdx = 0; MaskIdx != 2; ++MaskIdx) {
7669 // Match by SDValue identity so that (X & M1) ^ M2 is never folded
7670 // unless M1 and M2 are the same value. Canonicalize before
7671 // instruction selection, where the AND operand may already have been
7672 // selected to a target machine node.
7673 if (And.getOperand(MaskIdx) != Mask)
7674 continue;
7675 SDLoc DL(N);
7676 SDValue X = And.getOperand(1 - MaskIdx);
7677 return DAG.getNode(ISD::AND, DL, VT, Mask, DAG.getNOT(DL, X, VT));
7678 }
7679 }
7680 return SDValue();
7681}
7682
7684 ExtType = ISD::NON_EXTLOAD;
7685
7686 switch (V.getNode()->getOpcode()) {
7687 case ISD::LOAD: {
7688 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
7689 if ((LoadNode->getMemoryVT() == MVT::i8) ||
7690 (LoadNode->getMemoryVT() == MVT::i16)) {
7691 ExtType = LoadNode->getExtensionType();
7692 return true;
7693 }
7694 return false;
7695 }
7696 case ISD::AssertSext: {
7697 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
7698 if ((TypeNode->getVT() == MVT::i8) || (TypeNode->getVT() == MVT::i16)) {
7699 ExtType = ISD::SEXTLOAD;
7700 return true;
7701 }
7702 return false;
7703 }
7704 case ISD::AssertZext: {
7705 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
7706 if ((TypeNode->getVT() == MVT::i8) || (TypeNode->getVT() == MVT::i16)) {
7707 ExtType = ISD::ZEXTLOAD;
7708 return true;
7709 }
7710 return false;
7711 }
7712 default:
7713 return false;
7714 }
7715
7716 return false;
7717}
7718
7719// Fold a lane-mask extraction that is only compared against zero into one of
7720// all-lane check instructions, which write the results into fcc register, so
7721// BCEQZ could use it directly.
7722//
7723// (VMSKLTZ X) != 0 -> VSETNEZ.V X
7724// (VMSKLTZ X) == 0 -> VSETEQZ.V X
7725//
7726// This is valid when X is the result of a vector compare instruction,
7727// so each lane of X has to be all-ones or all-zeros.
7729 const SDLoc &DL, SelectionDAG &DAG,
7731 if (CC != ISD::SETEQ && CC != ISD::SETNE)
7732 return SDValue();
7733 if (!isNullConstant(RHS))
7734 return SDValue();
7735
7736 unsigned MskOpc = LHS.getOpcode();
7737 if (MskOpc != LoongArchISD::VMSKLTZ && MskOpc != LoongArchISD::XVMSKLTZ)
7738 return SDValue();
7739 // Keeping the mask alive for another user would defeat the purpose.
7740 if (!LHS.hasOneUse())
7741 return SDValue();
7742
7743 SDValue Src = LHS.getOperand(0);
7744 EVT SrcVT = Src.getValueType();
7745 // Make sure every lane is all-ones or all-zeros.
7746 if (!SrcVT.isVector() ||
7747 DAG.ComputeNumSignBits(Src) != SrcVT.getScalarSizeInBits())
7748 return SDValue();
7749
7750 return DAG.getNode(CC == ISD::SETNE ? LoongArchISD::VANYNONZERO
7751 : LoongArchISD::VALLZERO,
7752 DL, Subtarget.getGRLenVT(), Src);
7753}
7754
7755// Eliminate redundant truncation and zero-extension nodes.
7756// * Case 1:
7757// +------------+ +------------+ +------------+
7758// | Input1 | | Input2 | | CC |
7759// +------------+ +------------+ +------------+
7760// | | |
7761// V V +----+
7762// +------------+ +------------+ |
7763// | TRUNCATE | | TRUNCATE | |
7764// +------------+ +------------+ |
7765// | | |
7766// V V |
7767// +------------+ +------------+ |
7768// | ZERO_EXT | | ZERO_EXT | |
7769// +------------+ +------------+ |
7770// | | |
7771// | +-------------+ |
7772// V V | |
7773// +----------------+ | |
7774// | AND | | |
7775// +----------------+ | |
7776// | | |
7777// +---------------+ | |
7778// | | |
7779// V V V
7780// +-------------+
7781// | CMP |
7782// +-------------+
7783// * Case 2:
7784// +------------+ +------------+ +-------------+ +------------+ +------------+
7785// | Input1 | | Input2 | | Constant -1 | | Constant 0 | | CC |
7786// +------------+ +------------+ +-------------+ +------------+ +------------+
7787// | | | | |
7788// V | | | |
7789// +------------+ | | | |
7790// | XOR |<---------------------+ | |
7791// +------------+ | | |
7792// | | | |
7793// V V +---------------+ |
7794// +------------+ +------------+ | |
7795// | TRUNCATE | | TRUNCATE | | +-------------------------+
7796// +------------+ +------------+ | |
7797// | | | |
7798// V V | |
7799// +------------+ +------------+ | |
7800// | ZERO_EXT | | ZERO_EXT | | |
7801// +------------+ +------------+ | |
7802// | | | |
7803// V V | |
7804// +----------------+ | |
7805// | AND | | |
7806// +----------------+ | |
7807// | | |
7808// +---------------+ | |
7809// | | |
7810// V V V
7811// +-------------+
7812// | CMP |
7813// +-------------+
7817 ISD::CondCode CC = N->getOperandCondCode(2);
7818
7819 if (N->getValueType(0) == Subtarget.getGRLenVT())
7820 if (SDValue V = foldVMskZeroTest(N->getOperand(0), N->getOperand(1), CC,
7821 SDLoc(N), DAG, Subtarget))
7822 return V;
7823
7824 SDNode *AndNode = N->getOperand(0).getNode();
7825 if (AndNode->getOpcode() != ISD::AND)
7826 return SDValue();
7827
7828 SDValue AndInputValue2 = AndNode->getOperand(1);
7829 if (AndInputValue2.getOpcode() != ISD::ZERO_EXTEND)
7830 return SDValue();
7831
7832 SDValue CmpInputValue = N->getOperand(1);
7833 SDValue AndInputValue1 = AndNode->getOperand(0);
7834 if (AndInputValue1.getOpcode() == ISD::XOR) {
7835 if (CC != ISD::SETEQ && CC != ISD::SETNE)
7836 return SDValue();
7837 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndInputValue1.getOperand(1));
7838 if (!CN || !CN->isAllOnes())
7839 return SDValue();
7840 CN = dyn_cast<ConstantSDNode>(CmpInputValue);
7841 if (!CN || !CN->isZero())
7842 return SDValue();
7843 AndInputValue1 = AndInputValue1.getOperand(0);
7844 if (AndInputValue1.getOpcode() != ISD::ZERO_EXTEND)
7845 return SDValue();
7846 } else if (AndInputValue1.getOpcode() == ISD::ZERO_EXTEND) {
7847 if (AndInputValue2 != CmpInputValue)
7848 return SDValue();
7849 } else {
7850 return SDValue();
7851 }
7852
7853 SDValue TruncValue1 = AndInputValue1.getNode()->getOperand(0);
7854 if (TruncValue1.getOpcode() != ISD::TRUNCATE)
7855 return SDValue();
7856
7857 SDValue TruncValue2 = AndInputValue2.getNode()->getOperand(0);
7858 if (TruncValue2.getOpcode() != ISD::TRUNCATE)
7859 return SDValue();
7860
7861 SDValue TruncInputValue1 = TruncValue1.getNode()->getOperand(0);
7862 SDValue TruncInputValue2 = TruncValue2.getNode()->getOperand(0);
7863 ISD::LoadExtType ExtType1;
7864 ISD::LoadExtType ExtType2;
7865
7866 if (!checkValueWidth(TruncInputValue1, ExtType1) ||
7867 !checkValueWidth(TruncInputValue2, ExtType2))
7868 return SDValue();
7869
7870 if (TruncInputValue1->getValueType(0) != TruncInputValue2->getValueType(0) ||
7871 AndNode->getValueType(0) != TruncInputValue1->getValueType(0))
7872 return SDValue();
7873
7874 if ((ExtType2 != ISD::ZEXTLOAD) &&
7875 ((ExtType2 != ISD::SEXTLOAD) && (ExtType1 != ISD::SEXTLOAD)))
7876 return SDValue();
7877
7878 // These truncation and zero-extension nodes are not necessary, remove them.
7879 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N), AndNode->getValueType(0),
7880 TruncInputValue1, TruncInputValue2);
7881 SDValue NewSetCC =
7882 DAG.getSetCC(SDLoc(N), N->getValueType(0), NewAnd, TruncInputValue2, CC);
7883 DAG.ReplaceAllUsesWith(N, NewSetCC.getNode());
7884 return SDValue(N, 0);
7885}
7886
7887// Strip a single outer ISD::SIGN_EXTEND_INREG from \p V, if present, and
7888// return the inner value together with the narrow VT it was extending
7889// from. If no such node is present, returns \p V unchanged and an invalid
7890// EVT.
7891//
7892// i32 (and other sub-GRLen) arithmetic is legalized to operate on the full
7893// GRLen-width register, with a `sign_extend_inreg` re-normalizing the
7894// result back into the narrow type's range afterwards (see e.g. the
7895// `add i32` -> `add` + `sign_extend_inreg ..., i32` legalization). Any
7896// combine that reassociates such a binop must track and reapply this
7897// extension, otherwise the transformed code can produce a value whose
7898// high bits no longer match the narrow-type semantics.
7899static std::pair<SDValue, EVT> stripSignExtendInReg(SDValue V) {
7900 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
7901 return {V.getOperand(0), cast<VTSDNode>(V.getOperand(1))->getVT()};
7902 return {V, EVT()};
7903}
7904
7905// Try to match \p BinV (after optionally stripping an outer
7906// sign_extend_inreg) as a supported binary operation that has \p X as one
7907// of its operands, returning the matched opcode, the other operand (the
7908// "delta"), and the narrow VT of the sign_extend_inreg that was stripped
7909// (invalid EVT if none was present).
7910//
7911// For commutative ops (add/or/xor), \p X may be either operand, since
7912// `binop(X, Y) == binop(Y, X)` and the identity element (0) works on
7913// either side.
7914//
7915// For `sub`, the operation is NOT commutative: `sub(X, Y) != sub(Y, X)`.
7916// Only `sub(X, Y)` (i.e. \p X is the *minuend*, the first operand) can be
7917// rewritten using the identity `X - 0 == X`. If \p X were the *subtrahend*
7918// (second operand, i.e. the pattern is actually `sub(Y, X)`), there is no
7919// way to express `cond ? (Y - X) : X` (or the symmetric case) as
7920// `X op (select ...)` without introducing an extra negation, so that case
7921// must be rejected instead of "optimized" into worse code.
7922static std::tuple<unsigned, SDValue, EVT>
7924 auto [Inner, ExtVT] = stripSignExtendInReg(BinV);
7925
7926 unsigned Opc = Inner.getOpcode();
7927 switch (Opc) {
7928 case ISD::ADD:
7929 case ISD::OR:
7930 case ISD::XOR:
7931 if (Inner.getOperand(0) == X)
7932 return {Opc, Inner.getOperand(1), ExtVT};
7933 if (Inner.getOperand(1) == X)
7934 return {Opc, Inner.getOperand(0), ExtVT};
7935 return {0, SDValue(), EVT()};
7936 case ISD::SUB:
7937 // Only accept X as the minuend (first operand); see comment above.
7938 if (Inner.getOperand(0) == X)
7939 return {Opc, Inner.getOperand(1), ExtVT};
7940 return {0, SDValue(), EVT()};
7941 default:
7942 return {0, SDValue(), EVT()};
7943 }
7944}
7945
7946// Try to combine:
7947// select cond, binop(X, Y), X -> binop X, (select cond, Y, 0)
7948// select cond, X, binop(X, Y) -> binop X, (select cond, 0, Y)
7949// for binop in {add, or, xor, sub}, where 0 is the identity element of the
7950// respective operation, additionally handling the common legalized form
7951// where the binop result is wrapped in a `sign_extend_inreg` (as happens
7952// for sub-GRLen types such as i32 on a 64-bit GRLen target). See
7953// matchBinOpWithSharedOperand() for the restrictions applied to
7954// non-commutative operations (currently only `sub`).
7958 if (DCI.isBeforeLegalizeOps())
7959 return SDValue();
7960
7961 EVT VT = N->getValueType(0);
7962 // Restrict to the scalar GRLen integer type that maskeqz/masknez operate
7963 // on; this also naturally excludes float and vector selects.
7964 if (VT != Subtarget.getGRLenVT())
7965 return SDValue();
7966
7967 SDValue Cond = N->getOperand(0);
7968 SDValue TrueV = N->getOperand(1);
7969 SDValue FalseV = N->getOperand(2);
7970 SDLoc DL(N);
7971
7972 auto TryFold = [&](SDValue BinV, SDValue SharedV,
7973 bool BinIsTrueArm) -> SDValue {
7974 auto [Opc, Delta, ExtVT] = matchBinOpWithSharedOperand(BinV, SharedV);
7975 if (!Opc)
7976 return SDValue();
7977
7978 // Avoid infinite combine loops: bail out if Delta is trivially the
7979 // same node we would otherwise be selecting on (shouldn't normally
7980 // happen, but guards against degenerate/self-referential IR).
7981 if (Delta.getNode() == N)
7982 return SDValue();
7983
7984 SDValue Zero = DAG.getConstant(0, DL, VT);
7985 SDValue NewSel = BinIsTrueArm ? DAG.getSelect(DL, VT, Cond, Delta, Zero)
7986 : DAG.getSelect(DL, VT, Cond, Zero, Delta);
7987 SDValue NewBin = DAG.getNode(Opc, DL, VT, SharedV, NewSel);
7988
7989 // If the original binop result was normalized back into a narrower
7990 // type via sign_extend_inreg (e.g. i32 arithmetic on a 64-bit GRLen
7991 // target), the new binop must be re-normalized the same way: SharedV
7992 // is already known-sign-extended for that narrow type, but NewSel
7993 // (Delta or 0, selected) combined with SharedV via Opc can still
7994 // produce a 64-bit result whose high bits don't match the narrow
7995 // type's sign-extended representation.
7996 if (ExtVT != EVT())
7997 NewBin = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, NewBin,
7998 DAG.getValueType(ExtVT));
7999
8000 return NewBin;
8001 };
8002
8003 if (SDValue R = TryFold(TrueV, FalseV, /*BinIsTrueArm=*/true))
8004 return R;
8005 if (SDValue R = TryFold(FalseV, TrueV, /*BinIsTrueArm=*/false))
8006 return R;
8007
8008 return SDValue();
8009}
8010
8011// Combine (loongarch_bitrev_w (loongarch_revb_2w X)) to loongarch_bitrev_4b.
8015 if (DCI.isBeforeLegalizeOps())
8016 return SDValue();
8017
8018 SDValue Src = N->getOperand(0);
8019 if (Src.getOpcode() != LoongArchISD::REVB_2W)
8020 return SDValue();
8021
8022 return DAG.getNode(LoongArchISD::BITREV_4B, SDLoc(N), N->getValueType(0),
8023 Src.getOperand(0));
8024}
8025
8026// Perform common combines for BR_CC and SELECT_CC conditions.
8027static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL,
8029 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8030
8031 // As far as arithmetic right shift always saves the sign,
8032 // shift can be omitted.
8033 // Fold setlt (sra X, N), 0 -> setlt X, 0 and
8034 // setge (sra X, N), 0 -> setge X, 0
8035 if (isNullConstant(RHS) && (CCVal == ISD::SETGE || CCVal == ISD::SETLT) &&
8036 LHS.getOpcode() == ISD::SRA) {
8037 LHS = LHS.getOperand(0);
8038 return true;
8039 }
8040
8041 if (!ISD::isIntEqualitySetCC(CCVal))
8042 return false;
8043
8044 // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt)
8045 // Sometimes the setcc is introduced after br_cc/select_cc has been formed.
8046 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8047 LHS.getOperand(0).getValueType() == Subtarget.getGRLenVT()) {
8048 // If we're looking for eq 0 instead of ne 0, we need to invert the
8049 // condition.
8050 bool Invert = CCVal == ISD::SETEQ;
8051 CCVal = LHS.getOperandCondCode(2);
8052 if (Invert)
8053 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8054
8055 RHS = LHS.getOperand(1);
8056 LHS = LHS.getOperand(0);
8057 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8058
8059 CC = DAG.getCondCode(CCVal);
8060 return true;
8061 }
8062
8063 // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, GRLen-1-C), 0, ge/lt)
8064 if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() &&
8065 LHS.getOperand(1).getOpcode() == ISD::Constant) {
8066 SDValue LHS0 = LHS.getOperand(0);
8067 if (LHS0.getOpcode() == ISD::AND &&
8068 LHS0.getOperand(1).getOpcode() == ISD::Constant) {
8069 uint64_t Mask = LHS0.getConstantOperandVal(1);
8070 uint64_t ShAmt = LHS.getConstantOperandVal(1);
8071 if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) {
8072 CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
8073 CC = DAG.getCondCode(CCVal);
8074
8075 ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt;
8076 LHS = LHS0.getOperand(0);
8077 if (ShAmt != 0)
8078 LHS =
8079 DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0),
8080 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
8081 return true;
8082 }
8083 }
8084 }
8085
8086 // (X, 1, setne) -> (X, 0, seteq) if we can prove X is 0/1.
8087 // This can occur when legalizing some floating point comparisons.
8088 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8089 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8090 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8091 CC = DAG.getCondCode(CCVal);
8092 RHS = DAG.getConstant(0, DL, LHS.getValueType());
8093 return true;
8094 }
8095
8096 // Fold ((shl (extract_vector_elt X, I), GRLen - EleBits)), 0, eq/ne) ->
8097 // ((extract_vector_elt X, I), 0, eq/ne)
8098 if (isNullConstant(RHS) && (CCVal == ISD::SETEQ || CCVal == ISD::SETNE) &&
8099 LHS.getOpcode() == ISD::SHL && LHS.hasOneUse() &&
8100 isa<ConstantSDNode>(LHS.getOperand(1))) {
8101 SDValue Ext = LHS.getOperand(0);
8102 unsigned Sht = LHS.getConstantOperandVal(1);
8103 if (Ext.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8104 SDValue Vec = Ext.getOperand(0);
8105 unsigned EleBits = Vec.getScalarValueSizeInBits();
8106 if ((EleBits + Sht) == Subtarget.getGRLen()) {
8107 LHS = Ext;
8108 return true;
8109 }
8110 }
8111 }
8112
8113 // Fold (C1, C2, cond) -> (0, 0, seteq/setne)
8115 const LoongArchTargetLowering *TLI = Subtarget.getTargetLowering();
8116 EVT VT = LHS.getValueType();
8117 EVT SetCCResVT =
8118 TLI->getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8119 if (SDValue Folded = DAG.FoldSetCC(SetCCResVT, LHS, RHS, CCVal, DL)) {
8120 LHS = DAG.getConstant(0, DL, VT);
8121 RHS = DAG.getConstant(0, DL, VT);
8123 return true;
8124 }
8125 }
8126
8127 return false;
8128}
8129
8133 SDValue LHS = N->getOperand(1);
8134 SDValue RHS = N->getOperand(2);
8135 SDValue CC = N->getOperand(3);
8136 SDLoc DL(N);
8137
8138 // CC was folded into V, so always return ISD::SETNE is fine.
8140 DL, DAG, Subtarget))
8141 return DAG.getNode(LoongArchISD::BR_CC, DL, N->getValueType(0),
8142 N->getOperand(0), V,
8143 DAG.getConstant(0, DL, Subtarget.getGRLenVT()),
8144 DAG.getCondCode(ISD::SETNE), N->getOperand(4));
8145
8146 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
8147 return DAG.getNode(LoongArchISD::BR_CC, DL, N->getValueType(0),
8148 N->getOperand(0), LHS, RHS, CC, N->getOperand(4));
8149
8150 return SDValue();
8151}
8152
8156 // Transform
8157 SDValue LHS = N->getOperand(0);
8158 SDValue RHS = N->getOperand(1);
8159 SDValue CC = N->getOperand(2);
8160 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8161 SDValue TrueV = N->getOperand(3);
8162 SDValue FalseV = N->getOperand(4);
8163 SDLoc DL(N);
8164 EVT VT = N->getValueType(0);
8165
8166 // If the True and False values are the same, we don't need a select_cc.
8167 if (TrueV == FalseV)
8168 return TrueV;
8169
8170 // (select (x < 0), y, z) -> x >> (GRLEN - 1) & (y - z) + z
8171 // (select (x >= 0), y, z) -> x >> (GRLEN - 1) & (z - y) + y
8172 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
8174 (CCVal == ISD::CondCode::SETLT || CCVal == ISD::CondCode::SETGE)) {
8175 if (CCVal == ISD::CondCode::SETGE)
8176 std::swap(TrueV, FalseV);
8177
8178 int64_t TrueSImm = cast<ConstantSDNode>(TrueV)->getSExtValue();
8179 int64_t FalseSImm = cast<ConstantSDNode>(FalseV)->getSExtValue();
8180 // Only handle simm12, if it is not in this range, it can be considered as
8181 // register.
8182 if (isInt<12>(TrueSImm) && isInt<12>(FalseSImm) &&
8183 isInt<12>(TrueSImm - FalseSImm)) {
8184 SDValue SRA =
8185 DAG.getNode(ISD::SRA, DL, VT, LHS,
8186 DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT));
8187 SDValue AND =
8188 DAG.getNode(ISD::AND, DL, VT, SRA,
8189 DAG.getSignedConstant(TrueSImm - FalseSImm, DL, VT));
8190 return DAG.getNode(ISD::ADD, DL, VT, AND, FalseV);
8191 }
8192
8193 if (CCVal == ISD::CondCode::SETGE)
8194 std::swap(TrueV, FalseV);
8195 }
8196
8197 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
8198 return DAG.getNode(LoongArchISD::SELECT_CC, DL, N->getValueType(0),
8199 {LHS, RHS, CC, TrueV, FalseV});
8200
8201 return SDValue();
8202}
8203
8204template <unsigned N>
8206 SelectionDAG &DAG,
8208 bool IsSigned = false) {
8209 SDLoc DL(Node);
8210 auto *CImm = cast<ConstantSDNode>(Node->getOperand(ImmOp));
8211 // Check the ImmArg.
8212 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
8213 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
8214 DAG.getContext()->emitError(Node->getOperationName(0) +
8215 ": argument out of range.");
8216 return DAG.getNode(ISD::UNDEF, DL, Subtarget.getGRLenVT());
8217 }
8218 return DAG.getConstant(CImm->getZExtValue(), DL, Subtarget.getGRLenVT());
8219}
8220
8221template <unsigned N>
8222static SDValue lowerVectorSplatImm(SDNode *Node, unsigned ImmOp,
8223 SelectionDAG &DAG, bool IsSigned = false) {
8224 SDLoc DL(Node);
8225 EVT ResTy = Node->getValueType(0);
8226 auto *CImm = cast<ConstantSDNode>(Node->getOperand(ImmOp));
8227
8228 // Check the ImmArg.
8229 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
8230 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
8231 DAG.getContext()->emitError(Node->getOperationName(0) +
8232 ": argument out of range.");
8233 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8234 }
8235 return DAG.getConstant(
8237 IsSigned ? CImm->getSExtValue() : CImm->getZExtValue(), IsSigned),
8238 DL, ResTy);
8239}
8240
8242 SDLoc DL(Node);
8243 EVT ResTy = Node->getValueType(0);
8244 SDValue Vec = Node->getOperand(2);
8245 SDValue Mask = DAG.getConstant(Vec.getScalarValueSizeInBits() - 1, DL, ResTy);
8246 return DAG.getNode(ISD::AND, DL, ResTy, Vec, Mask);
8247}
8248
8250 SDLoc DL(Node);
8251 EVT ResTy = Node->getValueType(0);
8252 SDValue One = DAG.getConstant(1, DL, ResTy);
8253 SDValue Bit =
8254 DAG.getNode(ISD::SHL, DL, ResTy, One, truncateVecElts(Node, DAG));
8255
8256 return DAG.getNode(ISD::AND, DL, ResTy, Node->getOperand(1),
8257 DAG.getNOT(DL, Bit, ResTy));
8258}
8259
8260template <unsigned N>
8262 SDLoc DL(Node);
8263 EVT ResTy = Node->getValueType(0);
8264 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8265 // Check the unsigned ImmArg.
8266 if (!isUInt<N>(CImm->getZExtValue())) {
8267 DAG.getContext()->emitError(Node->getOperationName(0) +
8268 ": argument out of range.");
8269 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8270 }
8271
8272 APInt BitImm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8273 SDValue Mask = DAG.getConstant(~BitImm, DL, ResTy);
8274
8275 return DAG.getNode(ISD::AND, DL, ResTy, Node->getOperand(1), Mask);
8276}
8277
8278template <unsigned N>
8280 SDLoc DL(Node);
8281 EVT ResTy = Node->getValueType(0);
8282 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8283 // Check the unsigned ImmArg.
8284 if (!isUInt<N>(CImm->getZExtValue())) {
8285 DAG.getContext()->emitError(Node->getOperationName(0) +
8286 ": argument out of range.");
8287 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8288 }
8289
8290 APInt Imm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8291 SDValue BitImm = DAG.getConstant(Imm, DL, ResTy);
8292 return DAG.getNode(ISD::OR, DL, ResTy, Node->getOperand(1), BitImm);
8293}
8294
8295template <unsigned N>
8297 SDLoc DL(Node);
8298 EVT ResTy = Node->getValueType(0);
8299 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8300 // Check the unsigned ImmArg.
8301 if (!isUInt<N>(CImm->getZExtValue())) {
8302 DAG.getContext()->emitError(Node->getOperationName(0) +
8303 ": argument out of range.");
8304 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8305 }
8306
8307 APInt Imm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8308 SDValue BitImm = DAG.getConstant(Imm, DL, ResTy);
8309 return DAG.getNode(ISD::XOR, DL, ResTy, Node->getOperand(1), BitImm);
8310}
8311
8312template <unsigned W>
8314 unsigned ResOp) {
8315 unsigned Imm = N->getConstantOperandVal(2);
8316 if (!isUInt<W>(Imm)) {
8317 const StringRef ErrorMsg = "argument out of range";
8318 DAG.getContext()->emitError(N->getOperationName(0) + ": " + ErrorMsg + ".");
8319 return DAG.getUNDEF(N->getValueType(0));
8320 }
8321 SDLoc DL(N);
8322 SDValue Vec = N->getOperand(1);
8323 SDValue Idx = DAG.getConstant(Imm, DL, MVT::i32);
8325 return DAG.getNode(ResOp, DL, N->getValueType(0), Vec, Idx, EltVT);
8326}
8327
8328static SDValue
8332 SDLoc DL(N);
8333 switch (N->getConstantOperandVal(0)) {
8334 default:
8335 break;
8336 case Intrinsic::loongarch_lsx_vadd_b:
8337 case Intrinsic::loongarch_lsx_vadd_h:
8338 case Intrinsic::loongarch_lsx_vadd_w:
8339 case Intrinsic::loongarch_lsx_vadd_d:
8340 case Intrinsic::loongarch_lasx_xvadd_b:
8341 case Intrinsic::loongarch_lasx_xvadd_h:
8342 case Intrinsic::loongarch_lasx_xvadd_w:
8343 case Intrinsic::loongarch_lasx_xvadd_d:
8344 return DAG.getNode(ISD::ADD, DL, N->getValueType(0), N->getOperand(1),
8345 N->getOperand(2));
8346 case Intrinsic::loongarch_lsx_vaddi_bu:
8347 case Intrinsic::loongarch_lsx_vaddi_hu:
8348 case Intrinsic::loongarch_lsx_vaddi_wu:
8349 case Intrinsic::loongarch_lsx_vaddi_du:
8350 case Intrinsic::loongarch_lasx_xvaddi_bu:
8351 case Intrinsic::loongarch_lasx_xvaddi_hu:
8352 case Intrinsic::loongarch_lasx_xvaddi_wu:
8353 case Intrinsic::loongarch_lasx_xvaddi_du:
8354 return DAG.getNode(ISD::ADD, DL, N->getValueType(0), N->getOperand(1),
8355 lowerVectorSplatImm<5>(N, 2, DAG));
8356 case Intrinsic::loongarch_lsx_vsub_b:
8357 case Intrinsic::loongarch_lsx_vsub_h:
8358 case Intrinsic::loongarch_lsx_vsub_w:
8359 case Intrinsic::loongarch_lsx_vsub_d:
8360 case Intrinsic::loongarch_lasx_xvsub_b:
8361 case Intrinsic::loongarch_lasx_xvsub_h:
8362 case Intrinsic::loongarch_lasx_xvsub_w:
8363 case Intrinsic::loongarch_lasx_xvsub_d:
8364 return DAG.getNode(ISD::SUB, DL, N->getValueType(0), N->getOperand(1),
8365 N->getOperand(2));
8366 case Intrinsic::loongarch_lsx_vsubi_bu:
8367 case Intrinsic::loongarch_lsx_vsubi_hu:
8368 case Intrinsic::loongarch_lsx_vsubi_wu:
8369 case Intrinsic::loongarch_lsx_vsubi_du:
8370 case Intrinsic::loongarch_lasx_xvsubi_bu:
8371 case Intrinsic::loongarch_lasx_xvsubi_hu:
8372 case Intrinsic::loongarch_lasx_xvsubi_wu:
8373 case Intrinsic::loongarch_lasx_xvsubi_du:
8374 return DAG.getNode(ISD::SUB, DL, N->getValueType(0), N->getOperand(1),
8375 lowerVectorSplatImm<5>(N, 2, DAG));
8376 case Intrinsic::loongarch_lsx_vneg_b:
8377 case Intrinsic::loongarch_lsx_vneg_h:
8378 case Intrinsic::loongarch_lsx_vneg_w:
8379 case Intrinsic::loongarch_lsx_vneg_d:
8380 case Intrinsic::loongarch_lasx_xvneg_b:
8381 case Intrinsic::loongarch_lasx_xvneg_h:
8382 case Intrinsic::loongarch_lasx_xvneg_w:
8383 case Intrinsic::loongarch_lasx_xvneg_d:
8384 return DAG.getNode(
8385 ISD::SUB, DL, N->getValueType(0),
8386 DAG.getConstant(
8387 APInt(N->getValueType(0).getScalarType().getSizeInBits(), 0,
8388 /*isSigned=*/true),
8389 SDLoc(N), N->getValueType(0)),
8390 N->getOperand(1));
8391 case Intrinsic::loongarch_lsx_vmax_b:
8392 case Intrinsic::loongarch_lsx_vmax_h:
8393 case Intrinsic::loongarch_lsx_vmax_w:
8394 case Intrinsic::loongarch_lsx_vmax_d:
8395 case Intrinsic::loongarch_lasx_xvmax_b:
8396 case Intrinsic::loongarch_lasx_xvmax_h:
8397 case Intrinsic::loongarch_lasx_xvmax_w:
8398 case Intrinsic::loongarch_lasx_xvmax_d:
8399 return DAG.getNode(ISD::SMAX, DL, N->getValueType(0), N->getOperand(1),
8400 N->getOperand(2));
8401 case Intrinsic::loongarch_lsx_vmax_bu:
8402 case Intrinsic::loongarch_lsx_vmax_hu:
8403 case Intrinsic::loongarch_lsx_vmax_wu:
8404 case Intrinsic::loongarch_lsx_vmax_du:
8405 case Intrinsic::loongarch_lasx_xvmax_bu:
8406 case Intrinsic::loongarch_lasx_xvmax_hu:
8407 case Intrinsic::loongarch_lasx_xvmax_wu:
8408 case Intrinsic::loongarch_lasx_xvmax_du:
8409 return DAG.getNode(ISD::UMAX, DL, N->getValueType(0), N->getOperand(1),
8410 N->getOperand(2));
8411 case Intrinsic::loongarch_lsx_vmaxi_b:
8412 case Intrinsic::loongarch_lsx_vmaxi_h:
8413 case Intrinsic::loongarch_lsx_vmaxi_w:
8414 case Intrinsic::loongarch_lsx_vmaxi_d:
8415 case Intrinsic::loongarch_lasx_xvmaxi_b:
8416 case Intrinsic::loongarch_lasx_xvmaxi_h:
8417 case Intrinsic::loongarch_lasx_xvmaxi_w:
8418 case Intrinsic::loongarch_lasx_xvmaxi_d:
8419 return DAG.getNode(ISD::SMAX, DL, N->getValueType(0), N->getOperand(1),
8420 lowerVectorSplatImm<5>(N, 2, DAG, /*IsSigned=*/true));
8421 case Intrinsic::loongarch_lsx_vmaxi_bu:
8422 case Intrinsic::loongarch_lsx_vmaxi_hu:
8423 case Intrinsic::loongarch_lsx_vmaxi_wu:
8424 case Intrinsic::loongarch_lsx_vmaxi_du:
8425 case Intrinsic::loongarch_lasx_xvmaxi_bu:
8426 case Intrinsic::loongarch_lasx_xvmaxi_hu:
8427 case Intrinsic::loongarch_lasx_xvmaxi_wu:
8428 case Intrinsic::loongarch_lasx_xvmaxi_du:
8429 return DAG.getNode(ISD::UMAX, DL, N->getValueType(0), N->getOperand(1),
8430 lowerVectorSplatImm<5>(N, 2, DAG));
8431 case Intrinsic::loongarch_lsx_vmin_b:
8432 case Intrinsic::loongarch_lsx_vmin_h:
8433 case Intrinsic::loongarch_lsx_vmin_w:
8434 case Intrinsic::loongarch_lsx_vmin_d:
8435 case Intrinsic::loongarch_lasx_xvmin_b:
8436 case Intrinsic::loongarch_lasx_xvmin_h:
8437 case Intrinsic::loongarch_lasx_xvmin_w:
8438 case Intrinsic::loongarch_lasx_xvmin_d:
8439 return DAG.getNode(ISD::SMIN, DL, N->getValueType(0), N->getOperand(1),
8440 N->getOperand(2));
8441 case Intrinsic::loongarch_lsx_vmin_bu:
8442 case Intrinsic::loongarch_lsx_vmin_hu:
8443 case Intrinsic::loongarch_lsx_vmin_wu:
8444 case Intrinsic::loongarch_lsx_vmin_du:
8445 case Intrinsic::loongarch_lasx_xvmin_bu:
8446 case Intrinsic::loongarch_lasx_xvmin_hu:
8447 case Intrinsic::loongarch_lasx_xvmin_wu:
8448 case Intrinsic::loongarch_lasx_xvmin_du:
8449 return DAG.getNode(ISD::UMIN, DL, N->getValueType(0), N->getOperand(1),
8450 N->getOperand(2));
8451 case Intrinsic::loongarch_lsx_vmini_b:
8452 case Intrinsic::loongarch_lsx_vmini_h:
8453 case Intrinsic::loongarch_lsx_vmini_w:
8454 case Intrinsic::loongarch_lsx_vmini_d:
8455 case Intrinsic::loongarch_lasx_xvmini_b:
8456 case Intrinsic::loongarch_lasx_xvmini_h:
8457 case Intrinsic::loongarch_lasx_xvmini_w:
8458 case Intrinsic::loongarch_lasx_xvmini_d:
8459 return DAG.getNode(ISD::SMIN, DL, N->getValueType(0), N->getOperand(1),
8460 lowerVectorSplatImm<5>(N, 2, DAG, /*IsSigned=*/true));
8461 case Intrinsic::loongarch_lsx_vmini_bu:
8462 case Intrinsic::loongarch_lsx_vmini_hu:
8463 case Intrinsic::loongarch_lsx_vmini_wu:
8464 case Intrinsic::loongarch_lsx_vmini_du:
8465 case Intrinsic::loongarch_lasx_xvmini_bu:
8466 case Intrinsic::loongarch_lasx_xvmini_hu:
8467 case Intrinsic::loongarch_lasx_xvmini_wu:
8468 case Intrinsic::loongarch_lasx_xvmini_du:
8469 return DAG.getNode(ISD::UMIN, DL, N->getValueType(0), N->getOperand(1),
8470 lowerVectorSplatImm<5>(N, 2, DAG));
8471 case Intrinsic::loongarch_lsx_vmul_b:
8472 case Intrinsic::loongarch_lsx_vmul_h:
8473 case Intrinsic::loongarch_lsx_vmul_w:
8474 case Intrinsic::loongarch_lsx_vmul_d:
8475 case Intrinsic::loongarch_lasx_xvmul_b:
8476 case Intrinsic::loongarch_lasx_xvmul_h:
8477 case Intrinsic::loongarch_lasx_xvmul_w:
8478 case Intrinsic::loongarch_lasx_xvmul_d:
8479 return DAG.getNode(ISD::MUL, DL, N->getValueType(0), N->getOperand(1),
8480 N->getOperand(2));
8481 case Intrinsic::loongarch_lsx_vmadd_b:
8482 case Intrinsic::loongarch_lsx_vmadd_h:
8483 case Intrinsic::loongarch_lsx_vmadd_w:
8484 case Intrinsic::loongarch_lsx_vmadd_d:
8485 case Intrinsic::loongarch_lasx_xvmadd_b:
8486 case Intrinsic::loongarch_lasx_xvmadd_h:
8487 case Intrinsic::loongarch_lasx_xvmadd_w:
8488 case Intrinsic::loongarch_lasx_xvmadd_d: {
8489 EVT ResTy = N->getValueType(0);
8490 return DAG.getNode(ISD::ADD, SDLoc(N), ResTy, N->getOperand(1),
8491 DAG.getNode(ISD::MUL, SDLoc(N), ResTy, N->getOperand(2),
8492 N->getOperand(3)));
8493 }
8494 case Intrinsic::loongarch_lsx_vmsub_b:
8495 case Intrinsic::loongarch_lsx_vmsub_h:
8496 case Intrinsic::loongarch_lsx_vmsub_w:
8497 case Intrinsic::loongarch_lsx_vmsub_d:
8498 case Intrinsic::loongarch_lasx_xvmsub_b:
8499 case Intrinsic::loongarch_lasx_xvmsub_h:
8500 case Intrinsic::loongarch_lasx_xvmsub_w:
8501 case Intrinsic::loongarch_lasx_xvmsub_d: {
8502 EVT ResTy = N->getValueType(0);
8503 return DAG.getNode(ISD::SUB, SDLoc(N), ResTy, N->getOperand(1),
8504 DAG.getNode(ISD::MUL, SDLoc(N), ResTy, N->getOperand(2),
8505 N->getOperand(3)));
8506 }
8507 case Intrinsic::loongarch_lsx_vdiv_b:
8508 case Intrinsic::loongarch_lsx_vdiv_h:
8509 case Intrinsic::loongarch_lsx_vdiv_w:
8510 case Intrinsic::loongarch_lsx_vdiv_d:
8511 case Intrinsic::loongarch_lasx_xvdiv_b:
8512 case Intrinsic::loongarch_lasx_xvdiv_h:
8513 case Intrinsic::loongarch_lasx_xvdiv_w:
8514 case Intrinsic::loongarch_lasx_xvdiv_d:
8515 return DAG.getNode(ISD::SDIV, DL, N->getValueType(0), N->getOperand(1),
8516 N->getOperand(2));
8517 case Intrinsic::loongarch_lsx_vdiv_bu:
8518 case Intrinsic::loongarch_lsx_vdiv_hu:
8519 case Intrinsic::loongarch_lsx_vdiv_wu:
8520 case Intrinsic::loongarch_lsx_vdiv_du:
8521 case Intrinsic::loongarch_lasx_xvdiv_bu:
8522 case Intrinsic::loongarch_lasx_xvdiv_hu:
8523 case Intrinsic::loongarch_lasx_xvdiv_wu:
8524 case Intrinsic::loongarch_lasx_xvdiv_du:
8525 return DAG.getNode(ISD::UDIV, DL, N->getValueType(0), N->getOperand(1),
8526 N->getOperand(2));
8527 case Intrinsic::loongarch_lsx_vmod_b:
8528 case Intrinsic::loongarch_lsx_vmod_h:
8529 case Intrinsic::loongarch_lsx_vmod_w:
8530 case Intrinsic::loongarch_lsx_vmod_d:
8531 case Intrinsic::loongarch_lasx_xvmod_b:
8532 case Intrinsic::loongarch_lasx_xvmod_h:
8533 case Intrinsic::loongarch_lasx_xvmod_w:
8534 case Intrinsic::loongarch_lasx_xvmod_d:
8535 return DAG.getNode(ISD::SREM, DL, N->getValueType(0), N->getOperand(1),
8536 N->getOperand(2));
8537 case Intrinsic::loongarch_lsx_vmod_bu:
8538 case Intrinsic::loongarch_lsx_vmod_hu:
8539 case Intrinsic::loongarch_lsx_vmod_wu:
8540 case Intrinsic::loongarch_lsx_vmod_du:
8541 case Intrinsic::loongarch_lasx_xvmod_bu:
8542 case Intrinsic::loongarch_lasx_xvmod_hu:
8543 case Intrinsic::loongarch_lasx_xvmod_wu:
8544 case Intrinsic::loongarch_lasx_xvmod_du:
8545 return DAG.getNode(ISD::UREM, DL, N->getValueType(0), N->getOperand(1),
8546 N->getOperand(2));
8547 case Intrinsic::loongarch_lsx_vand_v:
8548 case Intrinsic::loongarch_lasx_xvand_v:
8549 return DAG.getNode(ISD::AND, DL, N->getValueType(0), N->getOperand(1),
8550 N->getOperand(2));
8551 case Intrinsic::loongarch_lsx_vor_v:
8552 case Intrinsic::loongarch_lasx_xvor_v:
8553 return DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8554 N->getOperand(2));
8555 case Intrinsic::loongarch_lsx_vxor_v:
8556 case Intrinsic::loongarch_lasx_xvxor_v:
8557 return DAG.getNode(ISD::XOR, DL, N->getValueType(0), N->getOperand(1),
8558 N->getOperand(2));
8559 case Intrinsic::loongarch_lsx_vnor_v:
8560 case Intrinsic::loongarch_lasx_xvnor_v: {
8561 SDValue Res = DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8562 N->getOperand(2));
8563 return DAG.getNOT(DL, Res, Res->getValueType(0));
8564 }
8565 case Intrinsic::loongarch_lsx_vandi_b:
8566 case Intrinsic::loongarch_lasx_xvandi_b:
8567 return DAG.getNode(ISD::AND, DL, N->getValueType(0), N->getOperand(1),
8568 lowerVectorSplatImm<8>(N, 2, DAG));
8569 case Intrinsic::loongarch_lsx_vori_b:
8570 case Intrinsic::loongarch_lasx_xvori_b:
8571 return DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8572 lowerVectorSplatImm<8>(N, 2, DAG));
8573 case Intrinsic::loongarch_lsx_vxori_b:
8574 case Intrinsic::loongarch_lasx_xvxori_b:
8575 return DAG.getNode(ISD::XOR, DL, N->getValueType(0), N->getOperand(1),
8576 lowerVectorSplatImm<8>(N, 2, DAG));
8577 case Intrinsic::loongarch_lsx_vsll_b:
8578 case Intrinsic::loongarch_lsx_vsll_h:
8579 case Intrinsic::loongarch_lsx_vsll_w:
8580 case Intrinsic::loongarch_lsx_vsll_d:
8581 case Intrinsic::loongarch_lasx_xvsll_b:
8582 case Intrinsic::loongarch_lasx_xvsll_h:
8583 case Intrinsic::loongarch_lasx_xvsll_w:
8584 case Intrinsic::loongarch_lasx_xvsll_d:
8585 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8586 truncateVecElts(N, DAG));
8587 case Intrinsic::loongarch_lsx_vslli_b:
8588 case Intrinsic::loongarch_lasx_xvslli_b:
8589 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8590 lowerVectorSplatImm<3>(N, 2, DAG));
8591 case Intrinsic::loongarch_lsx_vslli_h:
8592 case Intrinsic::loongarch_lasx_xvslli_h:
8593 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8594 lowerVectorSplatImm<4>(N, 2, DAG));
8595 case Intrinsic::loongarch_lsx_vslli_w:
8596 case Intrinsic::loongarch_lasx_xvslli_w:
8597 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8598 lowerVectorSplatImm<5>(N, 2, DAG));
8599 case Intrinsic::loongarch_lsx_vslli_d:
8600 case Intrinsic::loongarch_lasx_xvslli_d:
8601 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8602 lowerVectorSplatImm<6>(N, 2, DAG));
8603 case Intrinsic::loongarch_lsx_vsrl_b:
8604 case Intrinsic::loongarch_lsx_vsrl_h:
8605 case Intrinsic::loongarch_lsx_vsrl_w:
8606 case Intrinsic::loongarch_lsx_vsrl_d:
8607 case Intrinsic::loongarch_lasx_xvsrl_b:
8608 case Intrinsic::loongarch_lasx_xvsrl_h:
8609 case Intrinsic::loongarch_lasx_xvsrl_w:
8610 case Intrinsic::loongarch_lasx_xvsrl_d:
8611 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8612 truncateVecElts(N, DAG));
8613 case Intrinsic::loongarch_lsx_vsrli_b:
8614 case Intrinsic::loongarch_lasx_xvsrli_b:
8615 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8616 lowerVectorSplatImm<3>(N, 2, DAG));
8617 case Intrinsic::loongarch_lsx_vsrli_h:
8618 case Intrinsic::loongarch_lasx_xvsrli_h:
8619 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8620 lowerVectorSplatImm<4>(N, 2, DAG));
8621 case Intrinsic::loongarch_lsx_vsrli_w:
8622 case Intrinsic::loongarch_lasx_xvsrli_w:
8623 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8624 lowerVectorSplatImm<5>(N, 2, DAG));
8625 case Intrinsic::loongarch_lsx_vsrli_d:
8626 case Intrinsic::loongarch_lasx_xvsrli_d:
8627 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8628 lowerVectorSplatImm<6>(N, 2, DAG));
8629 case Intrinsic::loongarch_lsx_vsra_b:
8630 case Intrinsic::loongarch_lsx_vsra_h:
8631 case Intrinsic::loongarch_lsx_vsra_w:
8632 case Intrinsic::loongarch_lsx_vsra_d:
8633 case Intrinsic::loongarch_lasx_xvsra_b:
8634 case Intrinsic::loongarch_lasx_xvsra_h:
8635 case Intrinsic::loongarch_lasx_xvsra_w:
8636 case Intrinsic::loongarch_lasx_xvsra_d:
8637 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8638 truncateVecElts(N, DAG));
8639 case Intrinsic::loongarch_lsx_vsrai_b:
8640 case Intrinsic::loongarch_lasx_xvsrai_b:
8641 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8642 lowerVectorSplatImm<3>(N, 2, DAG));
8643 case Intrinsic::loongarch_lsx_vsrai_h:
8644 case Intrinsic::loongarch_lasx_xvsrai_h:
8645 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8646 lowerVectorSplatImm<4>(N, 2, DAG));
8647 case Intrinsic::loongarch_lsx_vsrai_w:
8648 case Intrinsic::loongarch_lasx_xvsrai_w:
8649 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8650 lowerVectorSplatImm<5>(N, 2, DAG));
8651 case Intrinsic::loongarch_lsx_vsrai_d:
8652 case Intrinsic::loongarch_lasx_xvsrai_d:
8653 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8654 lowerVectorSplatImm<6>(N, 2, DAG));
8655 case Intrinsic::loongarch_lsx_vclz_b:
8656 case Intrinsic::loongarch_lsx_vclz_h:
8657 case Intrinsic::loongarch_lsx_vclz_w:
8658 case Intrinsic::loongarch_lsx_vclz_d:
8659 case Intrinsic::loongarch_lasx_xvclz_b:
8660 case Intrinsic::loongarch_lasx_xvclz_h:
8661 case Intrinsic::loongarch_lasx_xvclz_w:
8662 case Intrinsic::loongarch_lasx_xvclz_d:
8663 return DAG.getNode(ISD::CTLZ, DL, N->getValueType(0), N->getOperand(1));
8664 case Intrinsic::loongarch_lsx_vpcnt_b:
8665 case Intrinsic::loongarch_lsx_vpcnt_h:
8666 case Intrinsic::loongarch_lsx_vpcnt_w:
8667 case Intrinsic::loongarch_lsx_vpcnt_d:
8668 case Intrinsic::loongarch_lasx_xvpcnt_b:
8669 case Intrinsic::loongarch_lasx_xvpcnt_h:
8670 case Intrinsic::loongarch_lasx_xvpcnt_w:
8671 case Intrinsic::loongarch_lasx_xvpcnt_d:
8672 return DAG.getNode(ISD::CTPOP, DL, N->getValueType(0), N->getOperand(1));
8673 case Intrinsic::loongarch_lsx_vbitclr_b:
8674 case Intrinsic::loongarch_lsx_vbitclr_h:
8675 case Intrinsic::loongarch_lsx_vbitclr_w:
8676 case Intrinsic::loongarch_lsx_vbitclr_d:
8677 case Intrinsic::loongarch_lasx_xvbitclr_b:
8678 case Intrinsic::loongarch_lasx_xvbitclr_h:
8679 case Intrinsic::loongarch_lasx_xvbitclr_w:
8680 case Intrinsic::loongarch_lasx_xvbitclr_d:
8681 return lowerVectorBitClear(N, DAG);
8682 case Intrinsic::loongarch_lsx_vbitclri_b:
8683 case Intrinsic::loongarch_lasx_xvbitclri_b:
8684 return lowerVectorBitClearImm<3>(N, DAG);
8685 case Intrinsic::loongarch_lsx_vbitclri_h:
8686 case Intrinsic::loongarch_lasx_xvbitclri_h:
8687 return lowerVectorBitClearImm<4>(N, DAG);
8688 case Intrinsic::loongarch_lsx_vbitclri_w:
8689 case Intrinsic::loongarch_lasx_xvbitclri_w:
8690 return lowerVectorBitClearImm<5>(N, DAG);
8691 case Intrinsic::loongarch_lsx_vbitclri_d:
8692 case Intrinsic::loongarch_lasx_xvbitclri_d:
8693 return lowerVectorBitClearImm<6>(N, DAG);
8694 case Intrinsic::loongarch_lsx_vbitset_b:
8695 case Intrinsic::loongarch_lsx_vbitset_h:
8696 case Intrinsic::loongarch_lsx_vbitset_w:
8697 case Intrinsic::loongarch_lsx_vbitset_d:
8698 case Intrinsic::loongarch_lasx_xvbitset_b:
8699 case Intrinsic::loongarch_lasx_xvbitset_h:
8700 case Intrinsic::loongarch_lasx_xvbitset_w:
8701 case Intrinsic::loongarch_lasx_xvbitset_d: {
8702 EVT VecTy = N->getValueType(0);
8703 SDValue One = DAG.getConstant(1, DL, VecTy);
8704 return DAG.getNode(
8705 ISD::OR, DL, VecTy, N->getOperand(1),
8706 DAG.getNode(ISD::SHL, DL, VecTy, One, truncateVecElts(N, DAG)));
8707 }
8708 case Intrinsic::loongarch_lsx_vbitseti_b:
8709 case Intrinsic::loongarch_lasx_xvbitseti_b:
8710 return lowerVectorBitSetImm<3>(N, DAG);
8711 case Intrinsic::loongarch_lsx_vbitseti_h:
8712 case Intrinsic::loongarch_lasx_xvbitseti_h:
8713 return lowerVectorBitSetImm<4>(N, DAG);
8714 case Intrinsic::loongarch_lsx_vbitseti_w:
8715 case Intrinsic::loongarch_lasx_xvbitseti_w:
8716 return lowerVectorBitSetImm<5>(N, DAG);
8717 case Intrinsic::loongarch_lsx_vbitseti_d:
8718 case Intrinsic::loongarch_lasx_xvbitseti_d:
8719 return lowerVectorBitSetImm<6>(N, DAG);
8720 case Intrinsic::loongarch_lsx_vbitrev_b:
8721 case Intrinsic::loongarch_lsx_vbitrev_h:
8722 case Intrinsic::loongarch_lsx_vbitrev_w:
8723 case Intrinsic::loongarch_lsx_vbitrev_d:
8724 case Intrinsic::loongarch_lasx_xvbitrev_b:
8725 case Intrinsic::loongarch_lasx_xvbitrev_h:
8726 case Intrinsic::loongarch_lasx_xvbitrev_w:
8727 case Intrinsic::loongarch_lasx_xvbitrev_d: {
8728 EVT VecTy = N->getValueType(0);
8729 SDValue One = DAG.getConstant(1, DL, VecTy);
8730 return DAG.getNode(
8731 ISD::XOR, DL, VecTy, N->getOperand(1),
8732 DAG.getNode(ISD::SHL, DL, VecTy, One, truncateVecElts(N, DAG)));
8733 }
8734 case Intrinsic::loongarch_lsx_vbitrevi_b:
8735 case Intrinsic::loongarch_lasx_xvbitrevi_b:
8736 return lowerVectorBitRevImm<3>(N, DAG);
8737 case Intrinsic::loongarch_lsx_vbitrevi_h:
8738 case Intrinsic::loongarch_lasx_xvbitrevi_h:
8739 return lowerVectorBitRevImm<4>(N, DAG);
8740 case Intrinsic::loongarch_lsx_vbitrevi_w:
8741 case Intrinsic::loongarch_lasx_xvbitrevi_w:
8742 return lowerVectorBitRevImm<5>(N, DAG);
8743 case Intrinsic::loongarch_lsx_vbitrevi_d:
8744 case Intrinsic::loongarch_lasx_xvbitrevi_d:
8745 return lowerVectorBitRevImm<6>(N, DAG);
8746 case Intrinsic::loongarch_lsx_vfadd_s:
8747 case Intrinsic::loongarch_lsx_vfadd_d:
8748 case Intrinsic::loongarch_lasx_xvfadd_s:
8749 case Intrinsic::loongarch_lasx_xvfadd_d:
8750 return DAG.getNode(ISD::FADD, DL, N->getValueType(0), N->getOperand(1),
8751 N->getOperand(2));
8752 case Intrinsic::loongarch_lsx_vfsub_s:
8753 case Intrinsic::loongarch_lsx_vfsub_d:
8754 case Intrinsic::loongarch_lasx_xvfsub_s:
8755 case Intrinsic::loongarch_lasx_xvfsub_d:
8756 return DAG.getNode(ISD::FSUB, DL, N->getValueType(0), N->getOperand(1),
8757 N->getOperand(2));
8758 case Intrinsic::loongarch_lsx_vfmul_s:
8759 case Intrinsic::loongarch_lsx_vfmul_d:
8760 case Intrinsic::loongarch_lasx_xvfmul_s:
8761 case Intrinsic::loongarch_lasx_xvfmul_d:
8762 return DAG.getNode(ISD::FMUL, DL, N->getValueType(0), N->getOperand(1),
8763 N->getOperand(2));
8764 case Intrinsic::loongarch_lsx_vfdiv_s:
8765 case Intrinsic::loongarch_lsx_vfdiv_d:
8766 case Intrinsic::loongarch_lasx_xvfdiv_s:
8767 case Intrinsic::loongarch_lasx_xvfdiv_d:
8768 return DAG.getNode(ISD::FDIV, DL, N->getValueType(0), N->getOperand(1),
8769 N->getOperand(2));
8770 case Intrinsic::loongarch_lsx_vfmadd_s:
8771 case Intrinsic::loongarch_lsx_vfmadd_d:
8772 case Intrinsic::loongarch_lasx_xvfmadd_s:
8773 case Intrinsic::loongarch_lasx_xvfmadd_d:
8774 return DAG.getNode(ISD::FMA, DL, N->getValueType(0), N->getOperand(1),
8775 N->getOperand(2), N->getOperand(3));
8776 case Intrinsic::loongarch_lsx_vinsgr2vr_b:
8777 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8778 N->getOperand(1), N->getOperand(2),
8780 case Intrinsic::loongarch_lsx_vinsgr2vr_h:
8781 case Intrinsic::loongarch_lasx_xvinsgr2vr_w:
8782 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8783 N->getOperand(1), N->getOperand(2),
8785 case Intrinsic::loongarch_lsx_vinsgr2vr_w:
8786 case Intrinsic::loongarch_lasx_xvinsgr2vr_d:
8787 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8788 N->getOperand(1), N->getOperand(2),
8790 case Intrinsic::loongarch_lsx_vinsgr2vr_d:
8791 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8792 N->getOperand(1), N->getOperand(2),
8794 case Intrinsic::loongarch_lsx_vreplgr2vr_b:
8795 case Intrinsic::loongarch_lsx_vreplgr2vr_h:
8796 case Intrinsic::loongarch_lsx_vreplgr2vr_w:
8797 case Intrinsic::loongarch_lsx_vreplgr2vr_d:
8798 case Intrinsic::loongarch_lasx_xvreplgr2vr_b:
8799 case Intrinsic::loongarch_lasx_xvreplgr2vr_h:
8800 case Intrinsic::loongarch_lasx_xvreplgr2vr_w:
8801 case Intrinsic::loongarch_lasx_xvreplgr2vr_d:
8802 return DAG.getNode(LoongArchISD::VREPLGR2VR, DL, N->getValueType(0),
8803 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getGRLenVT(),
8804 N->getOperand(1)));
8805 case Intrinsic::loongarch_lsx_vreplve_b:
8806 case Intrinsic::loongarch_lsx_vreplve_h:
8807 case Intrinsic::loongarch_lsx_vreplve_w:
8808 case Intrinsic::loongarch_lsx_vreplve_d:
8809 case Intrinsic::loongarch_lasx_xvreplve_b:
8810 case Intrinsic::loongarch_lasx_xvreplve_h:
8811 case Intrinsic::loongarch_lasx_xvreplve_w:
8812 case Intrinsic::loongarch_lasx_xvreplve_d:
8813 return DAG.getNode(LoongArchISD::VREPLVE, DL, N->getValueType(0),
8814 N->getOperand(1),
8815 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getGRLenVT(),
8816 N->getOperand(2)));
8817 case Intrinsic::loongarch_lsx_vpickve2gr_b:
8818 if (!Subtarget.is64Bit())
8819 return lowerVectorPickVE2GR<4>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8820 break;
8821 case Intrinsic::loongarch_lsx_vpickve2gr_h:
8822 case Intrinsic::loongarch_lasx_xvpickve2gr_w:
8823 if (!Subtarget.is64Bit())
8824 return lowerVectorPickVE2GR<3>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8825 break;
8826 case Intrinsic::loongarch_lsx_vpickve2gr_w:
8827 if (!Subtarget.is64Bit())
8828 return lowerVectorPickVE2GR<2>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8829 break;
8830 case Intrinsic::loongarch_lsx_vpickve2gr_bu:
8831 if (!Subtarget.is64Bit())
8832 return lowerVectorPickVE2GR<4>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8833 break;
8834 case Intrinsic::loongarch_lsx_vpickve2gr_hu:
8835 case Intrinsic::loongarch_lasx_xvpickve2gr_wu:
8836 if (!Subtarget.is64Bit())
8837 return lowerVectorPickVE2GR<3>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8838 break;
8839 case Intrinsic::loongarch_lsx_vpickve2gr_wu:
8840 if (!Subtarget.is64Bit())
8841 return lowerVectorPickVE2GR<2>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8842 break;
8843 case Intrinsic::loongarch_lsx_bz_b:
8844 case Intrinsic::loongarch_lsx_bz_h:
8845 case Intrinsic::loongarch_lsx_bz_w:
8846 case Intrinsic::loongarch_lsx_bz_d:
8847 case Intrinsic::loongarch_lasx_xbz_b:
8848 case Intrinsic::loongarch_lasx_xbz_h:
8849 case Intrinsic::loongarch_lasx_xbz_w:
8850 case Intrinsic::loongarch_lasx_xbz_d:
8851 if (!Subtarget.is64Bit())
8852 return DAG.getNode(LoongArchISD::VALL_ZERO, DL, N->getValueType(0),
8853 N->getOperand(1));
8854 break;
8855 case Intrinsic::loongarch_lsx_bz_v:
8856 case Intrinsic::loongarch_lasx_xbz_v:
8857 if (!Subtarget.is64Bit())
8858 return DAG.getNode(LoongArchISD::VANY_ZERO, DL, N->getValueType(0),
8859 N->getOperand(1));
8860 break;
8861 case Intrinsic::loongarch_lsx_bnz_b:
8862 case Intrinsic::loongarch_lsx_bnz_h:
8863 case Intrinsic::loongarch_lsx_bnz_w:
8864 case Intrinsic::loongarch_lsx_bnz_d:
8865 case Intrinsic::loongarch_lasx_xbnz_b:
8866 case Intrinsic::loongarch_lasx_xbnz_h:
8867 case Intrinsic::loongarch_lasx_xbnz_w:
8868 case Intrinsic::loongarch_lasx_xbnz_d:
8869 if (!Subtarget.is64Bit())
8870 return DAG.getNode(LoongArchISD::VALL_NONZERO, DL, N->getValueType(0),
8871 N->getOperand(1));
8872 break;
8873 case Intrinsic::loongarch_lsx_bnz_v:
8874 case Intrinsic::loongarch_lasx_xbnz_v:
8875 if (!Subtarget.is64Bit())
8876 return DAG.getNode(LoongArchISD::VANY_NONZERO, DL, N->getValueType(0),
8877 N->getOperand(1));
8878 break;
8879 case Intrinsic::loongarch_lasx_concat_128_s:
8880 case Intrinsic::loongarch_lasx_concat_128_d:
8881 case Intrinsic::loongarch_lasx_concat_128:
8882 return DAG.getNode(ISD::CONCAT_VECTORS, DL, N->getValueType(0),
8883 N->getOperand(1), N->getOperand(2));
8884 }
8885 return SDValue();
8886}
8887
8891 // If the input to MOVGR2FR_W_LA64 is just MOVFR2GR_S_LA64 the the
8892 // conversion is unnecessary and can be replaced with the
8893 // MOVFR2GR_S_LA64 operand.
8894 SDValue Op0 = N->getOperand(0);
8895 if (Op0.getOpcode() == LoongArchISD::MOVFR2GR_S_LA64)
8896 return Op0.getOperand(0);
8897 return SDValue();
8898}
8899
8903 // If the input to MOVFR2GR_S_LA64 is just MOVGR2FR_W_LA64 then the
8904 // conversion is unnecessary and can be replaced with the MOVGR2FR_W_LA64
8905 // operand.
8906 SDValue Op0 = N->getOperand(0);
8907 if (Op0->getOpcode() == LoongArchISD::MOVGR2FR_W_LA64) {
8908 assert(Op0.getOperand(0).getValueType() == N->getSimpleValueType(0) &&
8909 "Unexpected value type!");
8910 return Op0.getOperand(0);
8911 }
8912 return SDValue();
8913}
8914
8915static SDValue
8918 MVT VT = N->getSimpleValueType(0);
8919 unsigned NumBits = VT.getScalarSizeInBits();
8920
8921 // Simplify the inputs.
8923 APInt DemandedMask(APInt::getAllOnes(NumBits));
8924 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
8925 return SDValue(N, 0);
8926
8927 return SDValue();
8928}
8929
8930static SDValue
8934 SDValue Op0 = N->getOperand(0);
8935 SDLoc DL(N);
8936
8937 // If the input to SplitPairF64 is just BuildPairF64 then the operation is
8938 // redundant. Instead, use BuildPairF64's operands directly.
8939 if (Op0->getOpcode() == LoongArchISD::BUILD_PAIR_F64)
8940 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8941
8942 if (Op0->isUndef()) {
8943 SDValue Lo = DAG.getUNDEF(MVT::i32);
8944 SDValue Hi = DAG.getUNDEF(MVT::i32);
8945 return DCI.CombineTo(N, Lo, Hi);
8946 }
8947
8948 // It's cheaper to materialise two 32-bit integers than to load a double
8949 // from the constant pool and transfer it to integer registers through the
8950 // stack.
8952 APInt V = C->getValueAPF().bitcastToAPInt();
8953 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8954 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8955 return DCI.CombineTo(N, Lo, Hi);
8956 }
8957
8958 return SDValue();
8959}
8960
8961/// Do target-specific dag combines on LoongArchISD::VANDN nodes.
8965 SDValue N0 = N->getOperand(0);
8966 SDValue N1 = N->getOperand(1);
8967 MVT VT = N->getSimpleValueType(0);
8968 SDLoc DL(N);
8969
8970 // VANDN(undef, x) -> 0
8971 // VANDN(x, undef) -> 0
8972 if (N0.isUndef() || N1.isUndef())
8973 return DAG.getConstant(0, DL, VT);
8974
8975 // VANDN(0, x) -> x
8977 return N1;
8978
8979 // VANDN(x, 0) -> 0
8981 return DAG.getConstant(0, DL, VT);
8982
8983 // VANDN(x, -1) -> NOT(x) -> XOR(x, -1)
8985 return DAG.getNOT(DL, N0, VT);
8986
8987 // Turn VANDN back to AND if input is inverted.
8988 if (SDValue Not = isNOT(N0, DAG))
8989 return DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, Not), N1);
8990
8991 // VANDN(bitcast(shl(splat(1), y)), x)
8992 // -> bitcast(VANDN(shl(splat(1), y), bitcast(x)))
8993 // Perform the VANDN in the element type of the shift so that it can be
8994 // selected as [x]vbitclr.{b/h/w/d}.
8995 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
8996 SDValue Shl = N0.getOperand(0);
8997 EVT ShlVT = Shl.getValueType();
8998 APInt SplatVal;
8999 if (Shl.getOpcode() == ISD::SHL && ShlVT.isVector() && ShlVT.isInteger() &&
9000 ShlVT != VT && ShlVT.getSizeInBits() == VT.getSizeInBits() &&
9001 DAG.getTargetLoweringInfo().isTypeLegal(ShlVT) &&
9002 ISD::isConstantSplatVector(Shl.getOperand(0), SplatVal) &&
9003 SplatVal.isOne()) {
9004 SDValue V = DAG.getNode(LoongArchISD::VANDN, DL, ShlVT, Shl,
9005 DAG.getBitcast(ShlVT, N1));
9006 return DAG.getBitcast(VT, V);
9007 }
9008 }
9009
9010 // Folds for better commutativity:
9011 if (N1->hasOneUse()) {
9012 // VANDN(x,NOT(y)) -> AND(NOT(x),NOT(y)) -> NOT(OR(X,Y)).
9013 if (SDValue Not = isNOT(N1, DAG))
9014 return DAG.getNOT(
9015 DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)), VT);
9016
9017 // VANDN(x, SplatVector(Imm)) -> AND(NOT(x), NOT(SplatVector(~Imm)))
9018 // -> NOT(OR(x, SplatVector(-Imm))
9019 // Combination is performed only when VT is v16i8/v32i8, using `vnori.b` to
9020 // gain benefits.
9021 if (!DCI.isBeforeLegalizeOps() && (VT == MVT::v16i8 || VT == MVT::v32i8) &&
9022 N1.getOpcode() == ISD::BUILD_VECTOR) {
9023 if (SDValue SplatValue =
9024 cast<BuildVectorSDNode>(N1.getNode())->getSplatValue()) {
9025 if (!N1->isOnlyUserOf(SplatValue.getNode()))
9026 return SDValue();
9027
9028 if (auto *C = dyn_cast<ConstantSDNode>(SplatValue)) {
9029 uint8_t NCVal = static_cast<uint8_t>(~(C->getSExtValue()));
9030 SDValue Not =
9031 DAG.getSplat(VT, DL, DAG.getTargetConstant(NCVal, DL, MVT::i8));
9032 return DAG.getNOT(
9033 DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)),
9034 VT);
9035 }
9036 }
9037 }
9038 }
9039
9040 return SDValue();
9041}
9042
9043static SDValue ExtendSrcToDst(SDNode *N, SelectionDAG &DAG, unsigned ExtendOp) {
9044 SDLoc DL(N);
9045 EVT VT = N->getValueType(0);
9046 SDValue Src = N->getOperand(0);
9047 EVT SrcVT = Src.getValueType();
9048
9049 unsigned DstElts = VT.getVectorNumElements();
9050 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9051 unsigned DstEltBits = VT.getScalarSizeInBits();
9052
9053 if (SrcEltBits >= DstEltBits)
9054 return SDValue();
9055
9056 MVT WidenEltVT = MVT::getIntegerVT(DstEltBits);
9057 EVT WidenSrcVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, DstElts);
9058
9059 SDValue Extend = DAG.getNode(ExtendOp, DL, WidenSrcVT, Src);
9060 return DAG.getNode(N->getOpcode(), DL, VT, Extend);
9061}
9062
9063// Merge two 64 to 32 convert instructions into one,
9064// e.g.
9065// vffint.s.l $vr0, $vr1, $vr2
9066// will convert 4 si64 into 4 float at once.
9067// or
9068// vftintrz.w.d $vr0, $vr1, $vr2
9069// which will convert 4 double into 4 si32 at once.
9070// also deal with their 256-bits LASX version.
9071static SDValue MergeBlocksConvert(SDNode *N, SelectionDAG &DAG, unsigned Opcode,
9072 unsigned BlockBits) {
9073 SDLoc DL(N);
9074 MVT DstVT = N->getSimpleValueType(0);
9075 SDValue Src = N->getOperand(0);
9076 MVT SrcVT = Src.getSimpleValueType();
9077 unsigned SrcBits = SrcVT.getSizeInBits();
9078
9080 unsigned BlockNumElts = BlockBits / SrcVT.getScalarSizeInBits();
9081 MVT BlockVT = MVT::getVectorVT(SrcVT.getScalarType(), BlockNumElts);
9082 if (Src.getOpcode() == ISD::CONCAT_VECTORS &&
9083 Src.getOperand(0).getValueType() == BlockVT) {
9084 for (unsigned i = 0; i < Src.getNumOperands(); ++i)
9085 Blocks.push_back(Src.getOperand(i));
9086 } else if (SrcBits > BlockBits) {
9087 // Wider than one register: extract each BlockBits-wide sub-vector.
9088 for (unsigned i = 0; i < SrcBits / BlockBits; ++i)
9089 Blocks.push_back(
9090 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, BlockVT, Src,
9091 DAG.getVectorIdxConstant(i * BlockNumElts, DL)));
9092 } else {
9093 BlockBits = SrcBits;
9094 Blocks.push_back(Src);
9095 }
9096
9097 MVT NativeVecVT = MVT::getVectorVT(DstVT.getScalarType(),
9098 BlockBits / DstVT.getScalarSizeInBits());
9100 for (unsigned i = 0; i < Blocks.size(); i += 2) {
9101 SDValue Lo = Blocks[i];
9102 SDValue Hi = Blocks.size() > 1 ? Blocks[i + 1] : Lo;
9103 SDValue Res = DAG.getNode(Opcode, DL, NativeVecVT, Hi, Lo);
9104
9105 if (BlockBits == 256) {
9106 SDValue Undef = DAG.getUNDEF(NativeVecVT);
9107 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
9108 Res = DAG.getVectorShuffle(NativeVecVT, DL, Res, Undef, Mask);
9109 Res = DAG.getBitcast(NativeVecVT, Res);
9110 }
9111
9112 Parts.push_back(Res);
9113 }
9114
9115 if (Blocks.size() == 1)
9116 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, DstVT, Parts[0],
9117 DAG.getVectorIdxConstant(0, DL));
9118 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Parts);
9119}
9120
9124 SDLoc DL(N);
9125 EVT VT = N->getValueType(0);
9126 SDValue Src = N->getOperand(0);
9127 EVT SrcVT = Src.getValueType();
9128
9129 if (VT.isVector()) {
9130 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9131 unsigned DstEltBits = VT.getScalarSizeInBits();
9132 unsigned NumElts = VT.getVectorNumElements();
9133 unsigned BlockBits = Subtarget.hasExtLASX() ? 256 : 128;
9134
9135 // Sign-extend src to avoid scalarization.
9136 if (SrcEltBits <= DstEltBits)
9137 return ExtendSrcToDst(N, DAG, ISD::SIGN_EXTEND);
9138
9139 if (SrcEltBits != 64 || DstEltBits != 32 || !isPowerOf2_32(NumElts))
9140 return SDValue();
9141
9142 if (!SrcVT.isSimple() || !VT.isSimple())
9143 return SDValue();
9144
9145 // [x]vffint.s.l needs LSX and at least one full 128-bit source register.
9146 if (!Subtarget.hasExtLSX() || SrcVT.getSizeInBits() < 128)
9147 return SDValue();
9148
9149 // Combine [x]vffint.s.l for vector si64 to float conversion.
9150 return MergeBlocksConvert(N, DAG, LoongArchISD::VFFINT, BlockBits);
9151 }
9152
9153 if (VT != MVT::f32 && VT != MVT::f64)
9154 return SDValue();
9155 if (VT == MVT::f32 && !Subtarget.hasBasicF())
9156 return SDValue();
9157 if (VT == MVT::f64 && !Subtarget.hasBasicD())
9158 return SDValue();
9159
9160 // Only optimize when the source and destination types have the same width.
9161 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9162 return SDValue();
9163
9164 // If the result of an integer load is only used by an integer-to-float
9165 // conversion, use a fp load instead. This eliminates an integer-to-float-move
9166 // (movgr2fr) instruction.
9167 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse() &&
9168 // Do not change the width of a volatile load. This condition check is
9169 // inspired by AArch64.
9170 !cast<LoadSDNode>(Src)->isVolatile()) {
9171 LoadSDNode *LN0 = cast<LoadSDNode>(Src);
9172 SDValue Load = DAG.getLoad(VT, DL, LN0->getChain(), LN0->getBasePtr(),
9173 LN0->getPointerInfo(), LN0->getAlign(),
9174 LN0->getMemOperand()->getFlags());
9175
9176 // Make sure successors of the original load stay after it by updating them
9177 // to use the new Chain.
9178 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9179 return DAG.getNode(LoongArchISD::SITOF, SDLoc(N), VT, Load);
9180 }
9181
9182 return SDValue();
9183}
9184
9188 SDLoc DL(N);
9189 EVT VT = N->getValueType(0);
9190
9191 // Zero-extend src to avoid scalarization.
9192 if (VT.isVector())
9193 return ExtendSrcToDst(N, DAG, ISD::ZERO_EXTEND);
9194
9195 return SDValue();
9196}
9197
9198// Using [X]VFTINTRZ_W_D for double to signed 32-bit integer conversion.
9199// For example:
9200// v4i32 = fp_to_sint (concat_vectors v2f64, v2f64)
9201// Can be combined into:
9202// v4i32 = VFTINTRZ_W_D v2f64. v2f64
9206 if (!Subtarget.hasExtLSX())
9207 return SDValue();
9208
9209 SDLoc DL(N);
9210 EVT DstVT = N->getValueType(0);
9211 SDValue Src = N->getOperand(0);
9212 EVT SrcVT = Src.getValueType();
9213 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9214
9215 if (!DstVT.isVector() || !DstVT.isSimple() || !SrcVT.isSimple())
9216 return SDValue();
9217
9218 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9219 unsigned SrcBits = SrcVT.getSizeInBits();
9220 unsigned DstEltBits = DstVT.getScalarSizeInBits();
9221 unsigned NumElts = DstVT.getVectorNumElements();
9222 unsigned BlockBits = Subtarget.hasExtLASX() ? 256 : 128;
9223
9224 if (!isPowerOf2_32(NumElts) || !isPowerOf2_32(DstEltBits))
9225 return SDValue();
9226
9227 if (SrcBits % BlockBits != 0 && SrcBits != 128)
9228 return SDValue();
9229
9230 if (DstEltBits < 32) {
9231 MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(32), NumElts);
9232 SDValue Conv = DAG.getNode(N->getOpcode(), DL, PromoteVT, Src);
9233 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Conv);
9234 }
9235
9236 if (SrcEltBits != 64 || DstEltBits != 32)
9237 return SDValue();
9238
9239 if (!IsSigned) {
9240 // LASX already has pattern for double convert to uint32.
9241 if (Subtarget.hasExtLASX())
9242 return SDValue();
9243 MVT TmpVT = MVT::getVectorVT(MVT::i64, NumElts);
9244 SDValue Tmp = DAG.getNode(ISD::FP_TO_SINT, DL, TmpVT, Src);
9245 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Tmp);
9246 }
9247
9248 return MergeBlocksConvert(N, DAG, LoongArchISD::VFTINTRZ, BlockBits);
9249}
9250
9251// Try to widen AND, OR and XOR nodes to VT in order to remove casts around
9252// logical operations, like in the example below.
9253// or (and (truncate x, truncate y)),
9254// (xor (truncate z, build_vector (constants)))
9255// Given a target type \p VT, we generate
9256// or (and x, y), (xor z, zext(build_vector (constants)))
9257// given x, y and z are of type \p VT. We can do so, if operands are either
9258// truncates from VT types, the second operand is a vector of constants, can
9259// be recursively promoted or is an existing extension we can extend further.
9261 SelectionDAG &DAG,
9263 unsigned Depth) {
9264 // Limit recursion to avoid excessive compile times.
9266 return SDValue();
9267
9268 if (!ISD::isBitwiseLogicOp(N.getOpcode()))
9269 return SDValue();
9270
9271 SDValue N0 = N.getOperand(0);
9272 SDValue N1 = N.getOperand(1);
9273
9275 if (!TLI.isOperationLegalOrPromote(N.getOpcode(), VT))
9276 return SDValue();
9277
9278 if (SDValue NN0 =
9279 PromoteMaskArithmetic(N0, DL, VT, DAG, Subtarget, Depth + 1))
9280 N0 = NN0;
9281 else {
9282 // The left side has to be a 'trunc'.
9283 bool LHSTrunc = N0.getOpcode() == ISD::TRUNCATE &&
9284 N0.getOperand(0).getValueType() == VT;
9285 if (LHSTrunc)
9286 N0 = N0.getOperand(0);
9287 else
9288 return SDValue();
9289 }
9290
9291 if (SDValue NN1 =
9292 PromoteMaskArithmetic(N1, DL, VT, DAG, Subtarget, Depth + 1))
9293 N1 = NN1;
9294 else {
9295 // The right side has to be a 'trunc', a (foldable) constant or an
9296 // existing extension we can extend further.
9297 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
9298 N1.getOperand(0).getValueType() == VT;
9299 if (RHSTrunc)
9300 N1 = N1.getOperand(0);
9301 else if (ISD::isExtVecInRegOpcode(N1.getOpcode()) && VT.is256BitVector() &&
9302 Subtarget.hasExtLASX() && N1.hasOneUse())
9303 N1 = DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0));
9304 // On 32-bit platform, i64 is an illegal integer scalar type, and
9305 // FoldConstantArithmetic will fail for v4i64. This may be optimized in the
9306 // future.
9307 else if (SDValue Cst =
9309 N1 = Cst;
9310 else
9311 return SDValue();
9312 }
9313
9314 return DAG.getNode(N.getOpcode(), DL, VT, N0, N1);
9315}
9316
9317// On LASX the type v4i1/v8i1/v16i1 may be legalized to v4i32/v8i16/v16i8, which
9318// is LSX-sized register. In most cases we actually compare or select LASX-sized
9319// registers and mixing the two types creates horrible code. This method
9320// optimizes some of the transition sequences.
9322 SelectionDAG &DAG,
9324 EVT VT = N.getValueType();
9325 assert(VT.isVector() && "Expected vector type");
9326 assert((N.getOpcode() == ISD::ANY_EXTEND ||
9327 N.getOpcode() == ISD::ZERO_EXTEND ||
9328 N.getOpcode() == ISD::SIGN_EXTEND) &&
9329 "Invalid Node");
9330
9331 if (!Subtarget.hasExtLASX() || !VT.is256BitVector())
9332 return SDValue();
9333
9334 SDValue Narrow = N.getOperand(0);
9335 EVT NarrowVT = Narrow.getValueType();
9336
9337 // Generate the wide operation.
9338 SDValue Op = PromoteMaskArithmetic(Narrow, DL, VT, DAG, Subtarget, 0);
9339 if (!Op)
9340 return SDValue();
9341 switch (N.getOpcode()) {
9342 default:
9343 llvm_unreachable("Unexpected opcode");
9344 case ISD::ANY_EXTEND:
9345 return Op;
9346 case ISD::ZERO_EXTEND:
9347 return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
9348 case ISD::SIGN_EXTEND:
9349 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
9350 DAG.getValueType(NarrowVT));
9351 }
9352}
9353
9357 EVT VT = N->getValueType(0);
9358 SDLoc DL(N);
9359
9360 if (VT.isVector()) {
9361 if (SDValue R = PromoteMaskArithmetic(SDValue(N, 0), DL, DAG, Subtarget))
9362 return R;
9363
9364 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) ||
9365 N->getValueSizeInBits(0) != N->getOperand(0).getValueSizeInBits() * 2)
9366 return SDValue();
9367
9368 if (SDValue R = matchHalfOf128BitLanes(N->getOperand(0), /*isLow=*/false)) {
9369 if (N->getOpcode() == ISD::SIGN_EXTEND)
9370 return DAG.getNode(LoongArchISD::VEXTH, DL, VT, R);
9371 if (N->getOpcode() == ISD::ZERO_EXTEND)
9372 return DAG.getNode(LoongArchISD::VEXTH_U, DL, VT, R);
9373 }
9374 }
9375
9376 return SDValue();
9377}
9378
9379static SDValue
9383 SDLoc DL(N);
9384 EVT VT = N->getValueType(0);
9385
9386 if (VT.isVector() && N->getNumOperands() == 2)
9387 if (SDValue R = combineFP_ROUND(SDValue(N, 0), DL, DAG, Subtarget))
9388 return R;
9389
9390 return SDValue();
9391}
9392
9396 if (DCI.isBeforeLegalizeOps())
9397 return SDValue();
9398
9399 EVT VT = N->getValueType(0);
9400 if (!VT.isVector())
9401 return SDValue();
9402
9403 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9404 return SDValue();
9405
9406 EVT EltVT = VT.getVectorElementType();
9407 if (!EltVT.isInteger())
9408 return SDValue();
9409
9410 SDValue Cond = N->getOperand(0);
9411 SDValue TrueVal = N->getOperand(1);
9412 SDValue FalseVal = N->getOperand(2);
9413
9414 // match:
9415 //
9416 // vselect (setcc shift, 0, seteq),
9417 // x,
9418 // rounded_shift
9419
9420 if (Cond.getOpcode() != ISD::SETCC)
9421 return SDValue();
9422
9423 if (!ISD::isConstantSplatVectorAllZeros(Cond.getOperand(1)))
9424 return SDValue();
9425
9426 if (Cond.getOperandCondCode(2) != ISD::SETEQ)
9427 return SDValue();
9428
9429 SDValue Shift = Cond.getOperand(0);
9430
9431 // True branch must be original value:
9432 //
9433 // vselect cond, x, ...
9434
9435 SDValue X = TrueVal;
9436
9437 // Now match rounded shift pattern:
9438 //
9439 // add
9440 // (and
9441 // (srl X, shift-1)
9442 // 1)
9443 // (srl/sra X, shift)
9444
9445 if (FalseVal.getOpcode() != ISD::ADD)
9446 return SDValue();
9447
9448 SDValue Add0 = FalseVal.getOperand(0);
9449 SDValue Add1 = FalseVal.getOperand(1);
9450 SDValue And;
9451 SDValue Shr;
9452
9453 if (Add0.getOpcode() == ISD::AND) {
9454 And = Add0;
9455 Shr = Add1;
9456 } else if (Add1.getOpcode() == ISD::AND) {
9457 And = Add1;
9458 Shr = Add0;
9459 } else {
9460 return SDValue();
9461 }
9462
9463 // match:
9464 //
9465 // srl/sra X, shift
9466
9467 if (Shr.getOpcode() != ISD::SRL && Shr.getOpcode() != ISD::SRA)
9468 return SDValue();
9469
9470 if (Shr.getOperand(0) != X)
9471 return SDValue();
9472
9473 if (Shr.getOperand(1) != Shift)
9474 return SDValue();
9475
9476 // match:
9477 //
9478 // and
9479 // (srl X, shift-1)
9480 // 1
9481
9482 SDValue Srl = And.getOperand(0);
9483 SDValue One = And.getOperand(1);
9484 APInt SplatVal;
9485
9486 if (Srl.getOpcode() != ISD::SRL)
9487 return SDValue();
9488
9489 One = peekThroughBitcasts(One);
9490 if (!isConstantSplatVector(One, SplatVal, EltVT.getSizeInBits()))
9491 return SDValue();
9492
9493 if (SplatVal != 1)
9494 return SDValue();
9495
9496 if (Srl.getOperand(0) != X)
9497 return SDValue();
9498
9499 // match:
9500 //
9501 // shift-1
9502
9503 SDValue ShiftMinus1 = Srl.getOperand(1);
9504
9505 if (ShiftMinus1.getOpcode() != ISD::ADD)
9506 return SDValue();
9507
9508 if (ShiftMinus1.getOperand(0) != Shift)
9509 return SDValue();
9510
9511 if (!ISD::isConstantSplatVectorAllOnes(ShiftMinus1.getOperand(1)))
9512 return SDValue();
9513
9514 // We matched a rounded right shift pattern and can lower it
9515 // to a single vector rounded shift instruction.
9516
9517 SDLoc DL(N);
9518 return DAG.getNode(Shr.getOpcode() == ISD::SRL ? LoongArchISD::VSRLR
9519 : LoongArchISD::VSRAR,
9520 DL, VT, X, Shift);
9521}
9522
9526 if (!DCI.isBeforeLegalize())
9527 return SDValue();
9528
9529 SDLoc DL(N);
9530 EVT ResTy = N->getValueType(0);
9531 SDValue N0 = N->getOperand(0);
9532 SDValue N1 = N->getOperand(1);
9533
9534 bool HasLSXOnly = Subtarget.hasExtLSX() && !Subtarget.hasExtLASX();
9535 if (ResTy != MVT::v8i16 && ResTy != MVT::v4i32 && ResTy != MVT::v2i64 &&
9536 ResTy != MVT::i128 && ResTy != MVT::v16i16 && ResTy != MVT::v8i32 &&
9537 ResTy != MVT::v4i64 && ResTy != MVT::v2i128)
9538 return SDValue();
9539 if (HasLSXOnly && (ResTy.is256BitVector() || ResTy == MVT::v2i128))
9540 return SDValue();
9541
9542 // Combine:
9543 // ti,tii,...,tx = extract_vector_elt t0, {0,2,4,.../1,3,5,...}
9544 // tj,tjj,...,ty = extract_vector_elt t1, {0,2,4,.../1,3,5,...}
9545 // tm = BUILD_VECTOR ti,tii,...,tx (Only when ResTy != MVT::i128)
9546 // tn = BUILD_VECTOR tj,tjj,...,ty (Only when ResTy != MVT::i128)
9547 // ta = {sign/zero}_extend tm
9548 // tb = {sign/zero}_extend tn
9549 // tr = mul ta, tb
9550 // to:
9551 // tr = VMULW{EV/OD}[U/US] t0, t1
9552 auto getExtType = [](unsigned Op0, unsigned Op1) -> int {
9553 if (Op0 == ISD::SIGN_EXTEND && Op1 == ISD::SIGN_EXTEND)
9554 return 0;
9555 if (Op0 == ISD::ZERO_EXTEND && Op1 == ISD::ZERO_EXTEND)
9556 return 1;
9557 if (Op0 == ISD::ZERO_EXTEND && Op1 == ISD::SIGN_EXTEND)
9558 return 2;
9559 if (Op0 == ISD::SIGN_EXTEND && Op1 == ISD::ZERO_EXTEND)
9560 return 3;
9561 return -1;
9562 };
9563
9564 int ExtType = getExtType(N0.getOpcode(), N1.getOpcode());
9565 if (ExtType < 0)
9566 return SDValue();
9567
9568 // Avoid the regressions on LA64 introduced by combining
9569 // i128-type multiplications.
9570 bool IsScalar = (ResTy == MVT::i128);
9571 if (IsScalar && ExtType < 2 && Subtarget.is64Bit())
9572 return SDValue();
9573
9574 SDValue Src0 = N0.getOperand(0);
9575 SDValue Src1 = N1.getOperand(0);
9576 if (IsScalar && (Src0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9577 Src1.getOpcode() != ISD::EXTRACT_VECTOR_ELT))
9578 return SDValue();
9579 if (!IsScalar && (Src0.getOpcode() != ISD::BUILD_VECTOR ||
9580 Src1.getOpcode() != ISD::BUILD_VECTOR))
9581 return SDValue();
9582
9583 unsigned ResBits = ResTy.getScalarSizeInBits();
9584 unsigned Src0Bits = Src0.getValueType().getScalarSizeInBits();
9585 unsigned Src1Bits = Src1.getValueType().getScalarSizeInBits();
9586 if (Src0Bits != Src1Bits || ResBits != Src0Bits * 2)
9587 return SDValue();
9588
9589 // Collect all EXTRACT_VECTOR_ELT.
9591 if (IsScalar) {
9592 Elems.emplace_back(Src0, Src1);
9593 } else {
9594 for (unsigned i = 0; i < Src0.getNumOperands(); ++i)
9595 Elems.emplace_back(Src0.getOperand(i), Src1.getOperand(i));
9596 }
9597
9598 unsigned Index;
9599 SDValue OrigN0, OrigN1;
9600 bool First = true;
9601 for (auto &[Op0, Op1] : Elems) {
9602 // Each element must be EXTRACT_VECTOR_ELT.
9603 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9605 return SDValue();
9606
9607 // Check each EXTRACT_VECTOR_ELT's source vector and index.
9608 if (Op0.getOperand(1) != Op1.getOperand(1))
9609 return SDValue();
9610
9611 auto *IdxC = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9612 if (!IdxC)
9613 return SDValue();
9614
9615 unsigned CurIdx = IdxC->getZExtValue();
9616 if (First) {
9617 if (CurIdx != 0 && CurIdx != 1)
9618 return SDValue();
9619 OrigN0 = Op0.getOperand(0);
9620 OrigN1 = Op1.getOperand(0);
9621 First = false;
9622 } else {
9623 if (CurIdx != Index + 2 || Op0.getOperand(0) != OrigN0 ||
9624 Op1.getOperand(0) != OrigN1)
9625 return SDValue();
9626 }
9627 Index = CurIdx;
9628 }
9629
9630 if (OrigN0.getValueType() != OrigN1.getValueType())
9631 return SDValue();
9632 if (OrigN0.getValueType().getVectorNumElements() !=
9633 (IsScalar ? 1 : ResTy.getVectorNumElements()) * 2)
9634 return SDValue();
9635
9636 SDValue Result;
9637 EVT OrigTy = OrigN0.getValueType();
9638 bool IsEven = (Index % 2 == 0);
9639
9640 static const unsigned OpcTable[3][2] = {
9641 {LoongArchISD::VMULWOD, LoongArchISD::VMULWEV},
9642 {LoongArchISD::VMULWODU, LoongArchISD::VMULWEVU},
9643 {LoongArchISD::VMULWODUS, LoongArchISD::VMULWEVUS}};
9644
9645 if (ExtType == 3)
9646 Result = DAG.getNode(OpcTable[2][IsEven], DL, OrigTy, OrigN1, OrigN0);
9647 else
9648 Result = DAG.getNode(OpcTable[ExtType][IsEven], DL, OrigTy, OrigN0, OrigN1);
9649
9650 return DAG.getBitcast(ResTy, Result);
9651}
9652
9653static SDValue
9656 SelectionDAG &DAG = DCI.DAG;
9657 SDValue Src = N->getOperand(0);
9658 EVT VT = N->getValueType(0);
9659 EVT SrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9660 unsigned Opc = Src.getOpcode();
9661 SDLoc DL(N);
9662
9663 // Leave the sign extension in place when it feeds an xor with another
9664 // sign-extended value; the generic xor-of-sext_inregs combine can then
9665 // fold both extensions into a single one.
9666 if (N->hasOneUse()) {
9667 SDNode *User = N->use_begin()->getUser();
9668 if (User->getOpcode() == ISD::XOR) {
9669 SDValue Other = User->getOperand(0).getNode() == N ? User->getOperand(1)
9670 : User->getOperand(0);
9671 if (Other.getOpcode() == ISD::SIGN_EXTEND_INREG)
9672 return SDValue();
9673 }
9674 }
9675
9676 // Do not hide a sign-extended boolean from a compare against zero: the
9677 // generic combiner folds (setcc (sext_inreg X, i1), 0, setlt) back to X.
9678 for (SDNode *User : N->users()) {
9679 if (User->getOpcode() != ISD::SETCC)
9680 continue;
9681 if ((User->getOperand(0).getNode() == N &&
9683 (User->getOperand(1).getNode() == N &&
9685 return SDValue();
9686 }
9687
9688 // Fold (sext_inreg (shl X, Y), i32) -> (sll.w X, Y) iff Y u< 32.
9689 if (DCI.isAfterLegalizeDAG() && Subtarget.is64Bit() && SrcVT == MVT::i32 &&
9690 VT == MVT::i64 && Opc == ISD::SHL &&
9691 !isa<ConstantSDNode>(Src.getOperand(1)) &&
9692 DAG.computeKnownBits(Src.getOperand(1)).countMaxActiveBits() <= 5) {
9693 return DAG.getNode(LoongArchISD::SLL_W, DL, VT, Src.getOperand(0),
9694 Src.getOperand(1));
9695 }
9696
9697 // The SETCC/XOR folds replace the sign extension itself. When the result
9698 // has several users they do not save an instruction and can duplicate the
9699 // compare; leave it to the generic combiner.
9700 if (!N->hasOneUse())
9701 return SDValue();
9702
9703 // Similarly, a sign-extended boolean that feeds a sign-bit extraction is
9704 // usually part of a compare that the generic combiner can fold away.
9705 for (SDNode *User : N->users()) {
9706 if ((User->getOpcode() == ISD::SRL || User->getOpcode() == ISD::SRA) &&
9708 return SDValue();
9709 }
9710
9711 // Fold (sext_inreg (setcc X, Y, CC), i1) -> (sub 0, (setcc X, Y, CC)) if CC
9712 // can be selected with a single instruction, or
9713 // (add (setcc X, Y, inv(CC)), -1) if the inverted CC is cheaper. LoongArch
9714 // selects setge/setle/setuge/setule as slt + xori, so inverting such an
9715 // integer compare avoids the extra xor. Inverting replaces the original
9716 // setcc, so only do it when it has a single use; otherwise (e.g. an FP
9717 // compare shared with another user) this would introduce a second compare.
9718 if (Opc == ISD::SETCC && SrcVT == MVT::i1) {
9719 ISD::CondCode CC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
9720 if (Src.hasOneUse() && Src.getOperand(0).getValueType().isInteger()) {
9721 switch (CC) {
9722 case ISD::SETGE:
9723 case ISD::SETLE:
9724 case ISD::SETUGE:
9725 case ISD::SETULE:
9726 // (sub 0, X >= Y) == (add (X < Y), -1), etc.
9727 return DAG.getNode(
9728 ISD::ADD, DL, VT,
9729 DAG.getSetCC(
9730 SDLoc(N), Src.getValueType(), Src.getOperand(0),
9731 Src.getOperand(1),
9732 ISD::getSetCCInverse(CC, Src.getOperand(0).getValueType())),
9733 DAG.getAllOnesConstant(DL, VT));
9734 default:
9735 break;
9736 }
9737 }
9738 return DAG.getNegative(Src, DL, VT);
9739 }
9740
9741 // Fold (sext_inreg (xor (setcc), C), i1) -> (add (setcc), -1) where C is
9742 // either 1 or -1. Since setcc only produces 0 or 1, the xor only flips the
9743 // low bit, so the sign extension of that bit is -(1 - setcc) == setcc - 1.
9744 // The setcc may be wrapped in a truncate/any_extend when the boolean is
9745 // extended to VT (e.g. by a zext, which knows the upper bits are zero).
9746 if (Opc == ISD::XOR && SrcVT == MVT::i1 &&
9747 (isOneConstant(Src.getOperand(1)) ||
9748 isAllOnesConstant(Src.getOperand(1)))) {
9749 SDValue XorOp = Src.getOperand(0);
9750 if (XorOp.getOpcode() == ISD::TRUNCATE ||
9751 XorOp.getOpcode() == ISD::ANY_EXTEND)
9752 XorOp = XorOp.getOperand(0);
9753 if (XorOp.getOpcode() != ISD::SETCC)
9754 return SDValue();
9755 // The setcc may still have an i1 result type, in which case rebuild it
9756 // with VT so that both ADD operands have the same type. A setcc produces
9757 // a canonical 0/1 value, so this is exact while the any_extend leaves the
9758 // upper bits undefined.
9760 EVT OpVT = XorOp.getOperand(0).getValueType();
9761
9762 // Inverting an FP compare is free, so this fold does not save anything
9763 // and can duplicate a shared fcmp. Keep the original form.
9764 if (OpVT.isFloatingPoint())
9765 return SDValue();
9766
9767 // Reusing the original compare is only possible when the setcc is
9768 // otherwise dead. Inverting a shared compare duplicates it (e.g. an FP
9769 // compare used by a zext as well).
9770 if (!XorOp.hasOneUse())
9771 return SDValue();
9772
9773 // A constant compare with a greater-than style condition code cannot use
9774 // the slti/sltui immediate patterns; leave it to the generic combiner,
9775 // which canonicalizes it to setlt/setult first.
9776 if (isa<ConstantSDNode>(XorOp.getOperand(1)) && CC != ISD::SETLT &&
9777 CC != ISD::SETULT)
9778 return SDValue();
9779
9780 // The generic (sub X, (0 - Y)) -> (add X, Y) fold is better than
9781 // rewriting the sign-extended boolean here.
9782 if (N->hasOneUse() && N->use_begin()->getUser()->getOpcode() == ISD::SUB)
9783 return SDValue();
9784
9785 // For integer compares, sext(!setcc CC) == -(setcc inv(CC)). Only keep
9786 // CC (as add -1) when CC itself is the single-instruction form; otherwise
9787 // negate the inverted setcc, which also CSEs with an existing one.
9788 if (OpVT.isInteger() && CC != ISD::SETLT && CC != ISD::SETGT &&
9789 CC != ISD::SETULT && CC != ISD::SETUGT)
9790 return DAG.getNegative(DAG.getSetCC(DL, VT, XorOp.getOperand(0),
9791 XorOp.getOperand(1),
9792 ISD::getSetCCInverse(CC, OpVT)),
9793 DL, VT);
9794 if (XorOp.getValueType() != VT)
9795 XorOp =
9796 DAG.getSetCC(DL, VT, XorOp.getOperand(0), XorOp.getOperand(1), CC);
9797 return DAG.getNode(ISD::ADD, DL, VT, XorOp, DAG.getAllOnesConstant(DL, VT));
9798 }
9799
9800 return SDValue();
9801}
9802
9804 DAGCombinerInfo &DCI) const {
9805 SelectionDAG &DAG = DCI.DAG;
9806 switch (N->getOpcode()) {
9807 default:
9808 break;
9809 case ISD::ADD:
9810 return performADDCombine(N, DAG, DCI, Subtarget);
9811 case ISD::AND:
9812 return performANDCombine(N, DAG, DCI, Subtarget);
9813 case ISD::OR:
9814 return performORCombine(N, DAG, DCI, Subtarget);
9815 case ISD::XOR:
9816 return performXORCombine(N, DAG, Subtarget);
9817 case ISD::SETCC:
9818 return performSETCCCombine(N, DAG, DCI, Subtarget);
9819 case ISD::SELECT:
9820 return performSELECTCombine(N, DAG, DCI, Subtarget);
9821 case ISD::SHL:
9822 return performSHLCombine(N, DAG, DCI, Subtarget);
9823 case ISD::SRL:
9824 return performSRLCombine(N, DAG, DCI, Subtarget);
9825 case ISD::SUB:
9826 return performSUBCombine(N, DAG, DCI, Subtarget);
9827 case ISD::BITCAST:
9828 return performBITCASTCombine(N, DAG, DCI, Subtarget);
9829 case ISD::ANY_EXTEND:
9830 case ISD::ZERO_EXTEND:
9831 case ISD::SIGN_EXTEND:
9832 return performEXTENDCombine(N, DAG, DCI, Subtarget);
9834 return performSIGN_EXTEND_INREGCombine(N, DCI, Subtarget);
9835 case ISD::SINT_TO_FP:
9836 return performSINT_TO_FPCombine(N, DAG, DCI, Subtarget);
9837 case ISD::UINT_TO_FP:
9838 return performUINT_TO_FPCombine(N, DAG, DCI, Subtarget);
9839 case ISD::FP_TO_SINT:
9840 case ISD::FP_TO_UINT:
9841 return performFP_TO_INTCombine(N, DAG, DCI, Subtarget);
9842 case LoongArchISD::BITREV_W:
9843 return performBITREV_WCombine(N, DAG, DCI, Subtarget);
9844 case LoongArchISD::BR_CC:
9845 return performBR_CCCombine(N, DAG, DCI, Subtarget);
9846 case LoongArchISD::SELECT_CC:
9847 return performSELECT_CCCombine(N, DAG, DCI, Subtarget);
9849 return performINTRINSIC_WO_CHAINCombine(N, DAG, DCI, Subtarget);
9850 case LoongArchISD::MOVGR2FR_W_LA64:
9851 return performMOVGR2FR_WCombine(N, DAG, DCI, Subtarget);
9852 case LoongArchISD::MOVFR2GR_S_LA64:
9853 return performMOVFR2GR_SCombine(N, DAG, DCI, Subtarget);
9854 case LoongArchISD::CRC_W_B_W:
9855 case LoongArchISD::CRC_W_H_W:
9856 case LoongArchISD::CRCC_W_B_W:
9857 case LoongArchISD::CRCC_W_H_W:
9858 case LoongArchISD::VMSKLTZ:
9859 case LoongArchISD::XVMSKLTZ:
9860 return performDemandedBitsCombine(N, DAG, DCI);
9861 case LoongArchISD::SPLIT_PAIR_F64:
9862 return performSPLIT_PAIR_F64Combine(N, DAG, DCI, Subtarget);
9863 case LoongArchISD::VANDN:
9864 return performVANDNCombine(N, DAG, DCI, Subtarget);
9866 return performCONCAT_VECTORSCombine(N, DAG, DCI, Subtarget);
9867 case ISD::VSELECT:
9868 return performVSELECTCombine(N, DAG, DCI, Subtarget);
9869 case LoongArchISD::VPACKEV:
9870 case LoongArchISD::VPERMI:
9871 if (SDValue Result =
9872 combineFP_ROUND(SDValue(N, 0), SDLoc(N), DAG, Subtarget))
9873 return Result;
9874 break;
9875 case ISD::MUL:
9876 return performMULCombine(N, DAG, DCI, Subtarget);
9877 }
9878 return SDValue();
9879}
9880
9883 if (!ZeroDivCheck)
9884 return MBB;
9885
9886 // Build instructions:
9887 // MBB:
9888 // div(or mod) $dst, $dividend, $divisor
9889 // bne $divisor, $zero, SinkMBB
9890 // BreakMBB:
9891 // break 7 // BRK_DIVZERO
9892 // SinkMBB:
9893 // fallthrough
9894 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9895 MachineFunction::iterator It = ++MBB->getIterator();
9896 MachineFunction *MF = MBB->getParent();
9897 auto BreakMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9898 auto SinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9899 MF->insert(It, BreakMBB);
9900 MF->insert(It, SinkMBB);
9901
9902 // Transfer the remainder of MBB and its successor edges to SinkMBB.
9903 SinkMBB->splice(SinkMBB->end(), MBB, std::next(MI.getIterator()), MBB->end());
9904 SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9905
9906 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
9907 DebugLoc DL = MI.getDebugLoc();
9908 MachineOperand &Divisor = MI.getOperand(2);
9909 Register DivisorReg = Divisor.getReg();
9910
9911 // MBB:
9912 BuildMI(MBB, DL, TII.get(LoongArch::BNE))
9913 .addReg(DivisorReg, getKillRegState(Divisor.isKill()))
9914 .addReg(LoongArch::R0)
9915 .addMBB(SinkMBB);
9916 MBB->addSuccessor(BreakMBB);
9917 MBB->addSuccessor(SinkMBB);
9918
9919 // BreakMBB:
9920 // See linux header file arch/loongarch/include/uapi/asm/break.h for the
9921 // definition of BRK_DIVZERO.
9922 BuildMI(BreakMBB, DL, TII.get(LoongArch::BREAK)).addImm(7 /*BRK_DIVZERO*/);
9923 BreakMBB->addSuccessor(SinkMBB);
9924
9925 // Clear Divisor's kill flag.
9926 Divisor.setIsKill(false);
9927
9928 return SinkMBB;
9929}
9930
9931static MachineBasicBlock *
9934 unsigned InsOp;
9935 unsigned BroadcastOp;
9936 unsigned HalfSize;
9937 switch (MI.getOpcode()) {
9938 default:
9939 llvm_unreachable("Unexpected opcode");
9940 case LoongArch::PseudoXVINSGR2VR_B:
9941 HalfSize = 16;
9942 BroadcastOp = LoongArch::XVREPLGR2VR_B;
9943 InsOp = LoongArch::XVEXTRINS_B;
9944 break;
9945 case LoongArch::PseudoXVINSGR2VR_H:
9946 HalfSize = 8;
9947 BroadcastOp = LoongArch::XVREPLGR2VR_H;
9948 InsOp = LoongArch::XVEXTRINS_H;
9949 break;
9950 }
9951 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9952 const TargetRegisterClass *RC = &LoongArch::LASX256RegClass;
9953 const TargetRegisterClass *SubRC = &LoongArch::LSX128RegClass;
9954 DebugLoc DL = MI.getDebugLoc();
9956 // XDst = vector_insert XSrc, Elt, Idx
9957 Register XDst = MI.getOperand(0).getReg();
9958 Register XSrc = MI.getOperand(1).getReg();
9959 Register Elt = MI.getOperand(2).getReg();
9960 unsigned Idx = MI.getOperand(3).getImm();
9961
9962 if (XSrc.isVirtual() && MRI.getVRegDef(XSrc)->isImplicitDef() &&
9963 Idx < HalfSize) {
9964 Register ScratchSubReg1 = MRI.createVirtualRegister(SubRC);
9965 Register ScratchSubReg2 = MRI.createVirtualRegister(SubRC);
9966
9967 BuildMI(*BB, MI, DL, TII->get(LoongArch::COPY), ScratchSubReg1)
9968 .addReg(XSrc, {}, LoongArch::sub_128);
9969 BuildMI(*BB, MI, DL,
9970 TII->get(HalfSize == 8 ? LoongArch::VINSGR2VR_H
9971 : LoongArch::VINSGR2VR_B),
9972 ScratchSubReg2)
9973 .addReg(ScratchSubReg1)
9974 .addReg(Elt)
9975 .addImm(Idx);
9976
9977 BuildMI(*BB, MI, DL, TII->get(LoongArch::SUBREG_TO_REG), XDst)
9978 .addReg(ScratchSubReg2)
9979 .addImm(LoongArch::sub_128);
9980 } else {
9981 Register ScratchReg1 = MRI.createVirtualRegister(RC);
9982 Register ScratchReg2 = MRI.createVirtualRegister(RC);
9983
9984 BuildMI(*BB, MI, DL, TII->get(BroadcastOp), ScratchReg1).addReg(Elt);
9985
9986 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPERMI_Q), ScratchReg2)
9987 .addReg(ScratchReg1)
9988 .addReg(XSrc)
9989 .addImm(Idx >= HalfSize ? 48 : 18);
9990
9991 BuildMI(*BB, MI, DL, TII->get(InsOp), XDst)
9992 .addReg(XSrc)
9993 .addReg(ScratchReg2)
9994 .addImm((Idx >= HalfSize ? Idx - HalfSize : Idx) * 17);
9995 }
9996
9997 MI.eraseFromParent();
9998 return BB;
9999}
10000
10004 assert(Subtarget.hasExtLSX());
10005 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10006 const TargetRegisterClass *RC = &LoongArch::LSX128RegClass;
10007 DebugLoc DL = MI.getDebugLoc();
10009 Register Dst = MI.getOperand(0).getReg();
10010 Register Src = MI.getOperand(1).getReg();
10011
10012 unsigned BroadcastOp, CTOp, PickOp;
10013 switch (MI.getOpcode()) {
10014 default:
10015 llvm_unreachable("Unexpected opcode");
10016 case LoongArch::PseudoCTPOP_B:
10017 BroadcastOp = LoongArch::VREPLGR2VR_B;
10018 CTOp = LoongArch::VPCNT_B;
10019 PickOp = LoongArch::VPICKVE2GR_B;
10020 break;
10021 case LoongArch::PseudoCTPOP_H:
10022 case LoongArch::PseudoCTPOP_H_LA32:
10023 BroadcastOp = LoongArch::VREPLGR2VR_H;
10024 CTOp = LoongArch::VPCNT_H;
10025 PickOp = LoongArch::VPICKVE2GR_H;
10026 break;
10027 case LoongArch::PseudoCTPOP_W:
10028 case LoongArch::PseudoCTPOP_W_LA32:
10029 BroadcastOp = LoongArch::VREPLGR2VR_W;
10030 CTOp = LoongArch::VPCNT_W;
10031 PickOp = LoongArch::VPICKVE2GR_W;
10032 break;
10033 case LoongArch::PseudoCTPOP_D:
10034 BroadcastOp = LoongArch::VREPLGR2VR_D;
10035 CTOp = LoongArch::VPCNT_D;
10036 PickOp = LoongArch::VPICKVE2GR_D;
10037 break;
10038 }
10039
10040 Register ScratchReg1 = MRI.createVirtualRegister(RC);
10041 Register ScratchReg2 = MRI.createVirtualRegister(RC);
10042 BuildMI(*BB, MI, DL, TII->get(BroadcastOp), ScratchReg1).addReg(Src);
10043 BuildMI(*BB, MI, DL, TII->get(CTOp), ScratchReg2).addReg(ScratchReg1);
10044 BuildMI(*BB, MI, DL, TII->get(PickOp), Dst).addReg(ScratchReg2).addImm(0);
10045
10046 MI.eraseFromParent();
10047 return BB;
10048}
10049
10050static MachineBasicBlock *
10053 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10054 const TargetRegisterClass *RC = &LoongArch::LSX128RegClass;
10055 const LoongArchRegisterInfo *TRI = Subtarget.getRegisterInfo();
10057 Register Dst = MI.getOperand(0).getReg();
10058 Register Src = MI.getOperand(1).getReg();
10059 DebugLoc DL = MI.getDebugLoc();
10060 unsigned EleBits = 8;
10061 unsigned NotOpc = 0;
10062 unsigned MskOpc;
10063
10064 switch (MI.getOpcode()) {
10065 default:
10066 llvm_unreachable("Unexpected opcode");
10067 case LoongArch::PseudoVMSKLTZ_B:
10068 MskOpc = LoongArch::VMSKLTZ_B;
10069 break;
10070 case LoongArch::PseudoVMSKLTZ_H:
10071 MskOpc = LoongArch::VMSKLTZ_H;
10072 EleBits = 16;
10073 break;
10074 case LoongArch::PseudoVMSKLTZ_W:
10075 MskOpc = LoongArch::VMSKLTZ_W;
10076 EleBits = 32;
10077 break;
10078 case LoongArch::PseudoVMSKLTZ_D:
10079 MskOpc = LoongArch::VMSKLTZ_D;
10080 EleBits = 64;
10081 break;
10082 case LoongArch::PseudoVMSKGEZ_B:
10083 MskOpc = LoongArch::VMSKGEZ_B;
10084 break;
10085 case LoongArch::PseudoVMSKEQZ_B:
10086 MskOpc = LoongArch::VMSKNZ_B;
10087 NotOpc = LoongArch::VNOR_V;
10088 break;
10089 case LoongArch::PseudoVMSKNEZ_B:
10090 MskOpc = LoongArch::VMSKNZ_B;
10091 break;
10092 case LoongArch::PseudoXVMSKLTZ_B:
10093 MskOpc = LoongArch::XVMSKLTZ_B;
10094 RC = &LoongArch::LASX256RegClass;
10095 break;
10096 case LoongArch::PseudoXVMSKLTZ_H:
10097 MskOpc = LoongArch::XVMSKLTZ_H;
10098 RC = &LoongArch::LASX256RegClass;
10099 EleBits = 16;
10100 break;
10101 case LoongArch::PseudoXVMSKLTZ_W:
10102 MskOpc = LoongArch::XVMSKLTZ_W;
10103 RC = &LoongArch::LASX256RegClass;
10104 EleBits = 32;
10105 break;
10106 case LoongArch::PseudoXVMSKLTZ_D:
10107 MskOpc = LoongArch::XVMSKLTZ_D;
10108 RC = &LoongArch::LASX256RegClass;
10109 EleBits = 64;
10110 break;
10111 case LoongArch::PseudoXVMSKGEZ_B:
10112 MskOpc = LoongArch::XVMSKGEZ_B;
10113 RC = &LoongArch::LASX256RegClass;
10114 break;
10115 case LoongArch::PseudoXVMSKEQZ_B:
10116 MskOpc = LoongArch::XVMSKNZ_B;
10117 NotOpc = LoongArch::XVNOR_V;
10118 RC = &LoongArch::LASX256RegClass;
10119 break;
10120 case LoongArch::PseudoXVMSKNEZ_B:
10121 MskOpc = LoongArch::XVMSKNZ_B;
10122 RC = &LoongArch::LASX256RegClass;
10123 break;
10124 }
10125
10126 Register Msk = MRI.createVirtualRegister(RC);
10127 if (NotOpc) {
10128 Register Tmp = MRI.createVirtualRegister(RC);
10129 BuildMI(*BB, MI, DL, TII->get(MskOpc), Tmp).addReg(Src);
10130 BuildMI(*BB, MI, DL, TII->get(NotOpc), Msk).addReg(Tmp).addReg(Tmp);
10131 } else {
10132 BuildMI(*BB, MI, DL, TII->get(MskOpc), Msk).addReg(Src);
10133 }
10134
10135 if (TRI->getRegSizeInBits(*RC) > 128) {
10136 Register Lo = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
10137 Register Hi = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
10138 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPICKVE2GR_WU), Lo)
10139 .addReg(Msk)
10140 .addImm(0);
10141 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPICKVE2GR_WU), Hi)
10142 .addReg(Msk)
10143 .addImm(4);
10144 BuildMI(*BB, MI, DL,
10145 TII->get(Subtarget.is64Bit() ? LoongArch::BSTRINS_D
10146 : LoongArch::BSTRINS_W),
10147 Dst)
10148 .addReg(Lo)
10149 .addReg(Hi)
10150 .addImm(256 / EleBits - 1)
10151 .addImm(128 / EleBits);
10152 } else {
10153 BuildMI(*BB, MI, DL, TII->get(LoongArch::VPICKVE2GR_HU), Dst)
10154 .addReg(Msk)
10155 .addImm(0);
10156 }
10157
10158 MI.eraseFromParent();
10159 return BB;
10160}
10161
10162static MachineBasicBlock *
10165 assert(MI.getOpcode() == LoongArch::SplitPairF64Pseudo &&
10166 "Unexpected instruction");
10167
10168 MachineFunction &MF = *BB->getParent();
10169 DebugLoc DL = MI.getDebugLoc();
10171 Register LoReg = MI.getOperand(0).getReg();
10172 Register HiReg = MI.getOperand(1).getReg();
10173 Register SrcReg = MI.getOperand(2).getReg();
10174
10175 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVFR2GR_S_64), LoReg).addReg(SrcReg);
10176 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVFRH2GR_S), HiReg)
10177 .addReg(SrcReg, getKillRegState(MI.getOperand(2).isKill()));
10178 MI.eraseFromParent(); // The pseudo instruction is gone now.
10179 return BB;
10180}
10181
10182static MachineBasicBlock *
10185 assert(MI.getOpcode() == LoongArch::BuildPairF64Pseudo &&
10186 "Unexpected instruction");
10187
10188 MachineFunction &MF = *BB->getParent();
10189 DebugLoc DL = MI.getDebugLoc();
10192 Register TmpReg = MRI.createVirtualRegister(&LoongArch::FPR64RegClass);
10193 Register DstReg = MI.getOperand(0).getReg();
10194 Register LoReg = MI.getOperand(1).getReg();
10195 Register HiReg = MI.getOperand(2).getReg();
10196
10197 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVGR2FR_W_64), TmpReg)
10198 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()));
10199 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVGR2FRH_W), DstReg)
10200 .addReg(TmpReg)
10201 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()));
10202 MI.eraseFromParent(); // The pseudo instruction is gone now.
10203 return BB;
10204}
10205
10207 switch (MI.getOpcode()) {
10208 default:
10209 return false;
10210 case LoongArch::Select_GPR_Using_CC_GPR:
10211 return true;
10212 }
10213}
10214
10215static MachineBasicBlock *
10218 // To "insert" Select_* instructions, we actually have to insert the triangle
10219 // control-flow pattern. The incoming instructions know the destination vreg
10220 // to set, the condition code register to branch on, the true/false values to
10221 // select between, and the condcode to use to select the appropriate branch.
10222 //
10223 // We produce the following control flow:
10224 // HeadMBB
10225 // | \
10226 // | IfFalseMBB
10227 // | /
10228 // TailMBB
10229 //
10230 // When we find a sequence of selects we attempt to optimize their emission
10231 // by sharing the control flow. Currently we only handle cases where we have
10232 // multiple selects with the exact same condition (same LHS, RHS and CC).
10233 // The selects may be interleaved with other instructions if the other
10234 // instructions meet some requirements we deem safe:
10235 // - They are not pseudo instructions.
10236 // - They are debug instructions. Otherwise,
10237 // - They do not have side-effects, do not access memory and their inputs do
10238 // not depend on the results of the select pseudo-instructions.
10239 // The TrueV/FalseV operands of the selects cannot depend on the result of
10240 // previous selects in the sequence.
10241 // These conditions could be further relaxed. See the X86 target for a
10242 // related approach and more information.
10243
10244 Register LHS = MI.getOperand(1).getReg();
10245 Register RHS;
10246 if (MI.getOperand(2).isReg())
10247 RHS = MI.getOperand(2).getReg();
10248 auto CC = static_cast<unsigned>(MI.getOperand(3).getImm());
10249
10250 SmallVector<MachineInstr *, 4> SelectDebugValues;
10251 SmallSet<Register, 4> SelectDests;
10252 SelectDests.insert(MI.getOperand(0).getReg());
10253
10254 MachineInstr *LastSelectPseudo = &MI;
10255 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
10256 SequenceMBBI != E; ++SequenceMBBI) {
10257 if (SequenceMBBI->isDebugInstr())
10258 continue;
10259 if (isSelectPseudo(*SequenceMBBI)) {
10260 if (SequenceMBBI->getOperand(1).getReg() != LHS ||
10261 !SequenceMBBI->getOperand(2).isReg() ||
10262 SequenceMBBI->getOperand(2).getReg() != RHS ||
10263 SequenceMBBI->getOperand(3).getImm() != CC ||
10264 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
10265 SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
10266 break;
10267 LastSelectPseudo = &*SequenceMBBI;
10268 SequenceMBBI->collectDebugValues(SelectDebugValues);
10269 SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
10270 continue;
10271 }
10272 if (SequenceMBBI->hasUnmodeledSideEffects() ||
10273 SequenceMBBI->mayLoadOrStore() ||
10274 SequenceMBBI->usesCustomInsertionHook())
10275 break;
10276 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
10277 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
10278 }))
10279 break;
10280 }
10281
10282 const LoongArchInstrInfo &TII = *Subtarget.getInstrInfo();
10283 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10284 DebugLoc DL = MI.getDebugLoc();
10286
10287 MachineBasicBlock *HeadMBB = BB;
10288 MachineFunction *F = BB->getParent();
10289 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
10290 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
10291
10292 F->insert(I, IfFalseMBB);
10293 F->insert(I, TailMBB);
10294
10295 // Set the call frame size on entry to the new basic blocks.
10296 unsigned CallFrameSize = TII.getCallFrameSizeAt(*LastSelectPseudo);
10297 IfFalseMBB->setCallFrameSize(CallFrameSize);
10298 TailMBB->setCallFrameSize(CallFrameSize);
10299
10300 // Transfer debug instructions associated with the selects to TailMBB.
10301 for (MachineInstr *DebugInstr : SelectDebugValues) {
10302 TailMBB->push_back(DebugInstr->removeFromParent());
10303 }
10304
10305 // Move all instructions after the sequence to TailMBB.
10306 TailMBB->splice(TailMBB->end(), HeadMBB,
10307 std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
10308 // Update machine-CFG edges by transferring all successors of the current
10309 // block to the new block which will contain the Phi nodes for the selects.
10310 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
10311 // Set the successors for HeadMBB.
10312 HeadMBB->addSuccessor(IfFalseMBB);
10313 HeadMBB->addSuccessor(TailMBB);
10314
10315 // Insert appropriate branch.
10316 if (MI.getOperand(2).isImm())
10317 BuildMI(HeadMBB, DL, TII.get(CC))
10318 .addReg(LHS)
10319 .addImm(MI.getOperand(2).getImm())
10320 .addMBB(TailMBB);
10321 else
10322 BuildMI(HeadMBB, DL, TII.get(CC)).addReg(LHS).addReg(RHS).addMBB(TailMBB);
10323
10324 // IfFalseMBB just falls through to TailMBB.
10325 IfFalseMBB->addSuccessor(TailMBB);
10326
10327 // Create PHIs for all of the select pseudo-instructions.
10328 auto SelectMBBI = MI.getIterator();
10329 auto SelectEnd = std::next(LastSelectPseudo->getIterator());
10330 auto InsertionPoint = TailMBB->begin();
10331 while (SelectMBBI != SelectEnd) {
10332 auto Next = std::next(SelectMBBI);
10333 if (isSelectPseudo(*SelectMBBI)) {
10334 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
10335 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
10336 TII.get(LoongArch::PHI), SelectMBBI->getOperand(0).getReg())
10337 .addReg(SelectMBBI->getOperand(4).getReg())
10338 .addMBB(HeadMBB)
10339 .addReg(SelectMBBI->getOperand(5).getReg())
10340 .addMBB(IfFalseMBB);
10341 SelectMBBI->eraseFromParent();
10342 }
10343 SelectMBBI = Next;
10344 }
10345
10346 F->getProperties().resetNoPHIs();
10347 return TailMBB;
10348}
10349
10350MachineBasicBlock *LoongArchTargetLowering::EmitInstrWithCustomInserter(
10351 MachineInstr &MI, MachineBasicBlock *BB) const {
10352 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10353 DebugLoc DL = MI.getDebugLoc();
10354
10355 switch (MI.getOpcode()) {
10356 default:
10357 llvm_unreachable("Unexpected instr type to insert");
10358 case LoongArch::DIV_W:
10359 case LoongArch::DIV_WU:
10360 case LoongArch::MOD_W:
10361 case LoongArch::MOD_WU:
10362 case LoongArch::DIV_D:
10363 case LoongArch::DIV_DU:
10364 case LoongArch::MOD_D:
10365 case LoongArch::MOD_DU:
10366 return insertDivByZeroTrap(MI, BB);
10367 break;
10368 case LoongArch::WRFCSR: {
10369 BuildMI(*BB, MI, DL, TII->get(LoongArch::MOVGR2FCSR),
10370 LoongArch::FCSR0 + MI.getOperand(0).getImm())
10371 .addReg(MI.getOperand(1).getReg());
10372 MI.eraseFromParent();
10373 return BB;
10374 }
10375 case LoongArch::RDFCSR: {
10376 MachineInstr *ReadFCSR =
10377 BuildMI(*BB, MI, DL, TII->get(LoongArch::MOVFCSR2GR),
10378 MI.getOperand(0).getReg())
10379 .addReg(LoongArch::FCSR0 + MI.getOperand(1).getImm());
10380 ReadFCSR->getOperand(1).setIsUndef();
10381 MI.eraseFromParent();
10382 return BB;
10383 }
10384 case LoongArch::Select_GPR_Using_CC_GPR:
10385 return emitSelectPseudo(MI, BB, Subtarget);
10386 case LoongArch::BuildPairF64Pseudo:
10387 return emitBuildPairF64Pseudo(MI, BB, Subtarget);
10388 case LoongArch::SplitPairF64Pseudo:
10389 return emitSplitPairF64Pseudo(MI, BB, Subtarget);
10390 case LoongArch::PseudoXVINSGR2VR_B:
10391 case LoongArch::PseudoXVINSGR2VR_H:
10392 return emitPseudoXVINSGR2VR(MI, BB, Subtarget);
10393 case LoongArch::PseudoCTPOP_B:
10394 case LoongArch::PseudoCTPOP_H:
10395 case LoongArch::PseudoCTPOP_W:
10396 case LoongArch::PseudoCTPOP_D:
10397 case LoongArch::PseudoCTPOP_H_LA32:
10398 case LoongArch::PseudoCTPOP_W_LA32:
10399 return emitPseudoCTPOP(MI, BB, Subtarget);
10400 case LoongArch::PseudoVMSKLTZ_B:
10401 case LoongArch::PseudoVMSKLTZ_H:
10402 case LoongArch::PseudoVMSKLTZ_W:
10403 case LoongArch::PseudoVMSKLTZ_D:
10404 case LoongArch::PseudoVMSKGEZ_B:
10405 case LoongArch::PseudoVMSKEQZ_B:
10406 case LoongArch::PseudoVMSKNEZ_B:
10407 case LoongArch::PseudoXVMSKLTZ_B:
10408 case LoongArch::PseudoXVMSKLTZ_H:
10409 case LoongArch::PseudoXVMSKLTZ_W:
10410 case LoongArch::PseudoXVMSKLTZ_D:
10411 case LoongArch::PseudoXVMSKGEZ_B:
10412 case LoongArch::PseudoXVMSKEQZ_B:
10413 case LoongArch::PseudoXVMSKNEZ_B:
10414 return emitPseudoVMSKCOND(MI, BB, Subtarget);
10415 case TargetOpcode::STATEPOINT:
10416 // STATEPOINT is a pseudo instruction which has no implicit defs/uses
10417 // while bl call instruction (where statepoint will be lowered at the
10418 // end) has implicit def. This def is early-clobber as it will be set at
10419 // the moment of the call and earlier than any use is read.
10420 // Add this implicit dead def here as a workaround.
10421 MI.addOperand(*MI.getMF(),
10423 LoongArch::R1, /*isDef*/ true,
10424 /*isImp*/ true, /*isKill*/ false, /*isDead*/ true,
10425 /*isUndef*/ false, /*isEarlyClobber*/ true));
10426 if (!Subtarget.is64Bit())
10427 report_fatal_error("STATEPOINT is only supported on 64-bit targets");
10428 return emitPatchPoint(MI, BB);
10429 case LoongArch::PROBED_STACKALLOC_DYN:
10430 return emitDynamicProbedAlloc(MI, BB);
10431 }
10432}
10433
10435 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10436 unsigned *Fast) const {
10437 if (!Subtarget.hasUAL())
10438 return false;
10439
10440 // TODO: set reasonable speed number.
10441 if (Fast)
10442 *Fast = 1;
10443 return true;
10444}
10445
10446//===----------------------------------------------------------------------===//
10447// Calling Convention Implementation
10448//===----------------------------------------------------------------------===//
10449
10450// Eight general-purpose registers a0-a7 used for passing integer arguments,
10451// with a0-a1 reused to return values. Generally, the GPRs are used to pass
10452// fixed-point arguments, and floating-point arguments when no FPR is available
10453// or with soft float ABI.
10454const MCPhysReg ArgGPRs[] = {LoongArch::R4, LoongArch::R5, LoongArch::R6,
10455 LoongArch::R7, LoongArch::R8, LoongArch::R9,
10456 LoongArch::R10, LoongArch::R11};
10457
10458// PreserveNone calling convention:
10459// Arguments may be passed in any general-purpose registers except:
10460// - R1 : return address register
10461// - R22 : frame pointer
10462// - R31 : base pointer
10463//
10464// All general-purpose registers are treated as caller-saved,
10465// except R1 (RA) and R22 (FP).
10466//
10467// Non-volatile registers are allocated first so that a function
10468// can call normal functions without having to spill and reload
10469// argument registers.
10471 LoongArch::R23, LoongArch::R24, LoongArch::R25, LoongArch::R26,
10472 LoongArch::R27, LoongArch::R28, LoongArch::R29, LoongArch::R30,
10473 LoongArch::R4, LoongArch::R5, LoongArch::R6, LoongArch::R7,
10474 LoongArch::R8, LoongArch::R9, LoongArch::R10, LoongArch::R11,
10475 LoongArch::R12, LoongArch::R13, LoongArch::R14, LoongArch::R15,
10476 LoongArch::R16, LoongArch::R17, LoongArch::R18, LoongArch::R19,
10477 LoongArch::R20};
10478
10479// Eight floating-point registers fa0-fa7 used for passing floating-point
10480// arguments, and fa0-fa1 are also used to return values.
10481const MCPhysReg ArgFPR32s[] = {LoongArch::F0, LoongArch::F1, LoongArch::F2,
10482 LoongArch::F3, LoongArch::F4, LoongArch::F5,
10483 LoongArch::F6, LoongArch::F7};
10484// FPR32 and FPR64 alias each other.
10486 LoongArch::F0_64, LoongArch::F1_64, LoongArch::F2_64, LoongArch::F3_64,
10487 LoongArch::F4_64, LoongArch::F5_64, LoongArch::F6_64, LoongArch::F7_64};
10488
10489const MCPhysReg ArgVRs[] = {LoongArch::VR0, LoongArch::VR1, LoongArch::VR2,
10490 LoongArch::VR3, LoongArch::VR4, LoongArch::VR5,
10491 LoongArch::VR6, LoongArch::VR7};
10492
10493const MCPhysReg ArgXRs[] = {LoongArch::XR0, LoongArch::XR1, LoongArch::XR2,
10494 LoongArch::XR3, LoongArch::XR4, LoongArch::XR5,
10495 LoongArch::XR6, LoongArch::XR7};
10496
10498 switch (State.getCallingConv()) {
10500 if (!State.isVarArg())
10501 return State.AllocateReg(PreserveNoneArgGPRs);
10502 [[fallthrough]];
10503 default:
10504 return State.AllocateReg(ArgGPRs);
10505 }
10506}
10507
10508// Pass a 2*GRLen argument that has been split into two GRLen values through
10509// registers or the stack as necessary.
10510static bool CC_LoongArchAssign2GRLen(unsigned GRLen, CCState &State,
10511 CCValAssign VA1, ISD::ArgFlagsTy ArgFlags1,
10512 unsigned ValNo2, MVT ValVT2, MVT LocVT2,
10513 ISD::ArgFlagsTy ArgFlags2) {
10514 unsigned GRLenInBytes = GRLen / 8;
10515 if (Register Reg = allocateArgGPR(State)) {
10516 // At least one half can be passed via register.
10517 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10518 VA1.getLocVT(), CCValAssign::Full));
10519 } else {
10520 // Both halves must be passed on the stack, with proper alignment.
10521 Align StackAlign =
10522 std::max(Align(GRLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10523 State.addLoc(
10525 State.AllocateStack(GRLenInBytes, StackAlign),
10526 VA1.getLocVT(), CCValAssign::Full));
10527 State.addLoc(CCValAssign::getMem(
10528 ValNo2, ValVT2, State.AllocateStack(GRLenInBytes, Align(GRLenInBytes)),
10529 LocVT2, CCValAssign::Full));
10530 return false;
10531 }
10532 if (Register Reg = allocateArgGPR(State)) {
10533 // The second half can also be passed via register.
10534 State.addLoc(
10535 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10536 } else {
10537 // The second half is passed via the stack, without additional alignment.
10538 State.addLoc(CCValAssign::getMem(
10539 ValNo2, ValVT2, State.AllocateStack(GRLenInBytes, Align(GRLenInBytes)),
10540 LocVT2, CCValAssign::Full));
10541 }
10542 return false;
10543}
10544
10545// Implements the LoongArch calling convention. Returns true upon failure.
10547 unsigned ValNo, MVT ValVT,
10548 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
10549 CCState &State, bool IsRet, Type *OrigTy) {
10550 unsigned GRLen = DL.getLargestLegalIntTypeSizeInBits();
10551 assert((GRLen == 32 || GRLen == 64) && "Unspport GRLen");
10552 MVT GRLenVT = GRLen == 32 ? MVT::i32 : MVT::i64;
10553 MVT LocVT = ValVT;
10554
10555 // Any return value split into more than two values can't be returned
10556 // directly.
10557 if (IsRet && ValNo > 1)
10558 return true;
10559
10560 // If passing a variadic argument, or if no FPR is available.
10561 bool UseGPRForFloat = true;
10562
10563 switch (ABI) {
10564 default:
10565 llvm_unreachable("Unexpected ABI");
10566 break;
10571 UseGPRForFloat = ArgFlags.isVarArg();
10572 break;
10575 break;
10576 }
10577
10578 // If this is a variadic argument, the LoongArch calling convention requires
10579 // that it is assigned an 'even' or 'aligned' register if it has (2*GRLen)/8
10580 // byte alignment. An aligned register should be used regardless of whether
10581 // the original argument was split during legalisation or not. The argument
10582 // will not be passed by registers if the original type is larger than
10583 // 2*GRLen, so the register alignment rule does not apply.
10584 unsigned TwoGRLenInBytes = (2 * GRLen) / 8;
10585 if (ArgFlags.isVarArg() &&
10586 ArgFlags.getNonZeroOrigAlign() == TwoGRLenInBytes &&
10587 DL.getTypeAllocSize(OrigTy) == TwoGRLenInBytes) {
10588 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10589 // Skip 'odd' register if necessary.
10590 if (RegIdx != std::size(ArgGPRs) && RegIdx % 2 == 1)
10591 State.AllocateReg(ArgGPRs);
10592 }
10593
10594 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10595 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10596 State.getPendingArgFlags();
10597
10598 assert(PendingLocs.size() == PendingArgFlags.size() &&
10599 "PendingLocs and PendingArgFlags out of sync");
10600
10601 // FPR32 and FPR64 alias each other.
10602 if (State.getFirstUnallocated(ArgFPR32s) == std::size(ArgFPR32s))
10603 UseGPRForFloat = true;
10604
10605 if (UseGPRForFloat && ValVT == MVT::f32) {
10606 LocVT = GRLenVT;
10607 LocInfo = CCValAssign::BCvt;
10608 } else if (UseGPRForFloat && GRLen == 64 && ValVT == MVT::f64) {
10609 LocVT = MVT::i64;
10610 LocInfo = CCValAssign::BCvt;
10611 } else if (UseGPRForFloat && GRLen == 32 && ValVT == MVT::f64) {
10612 // Handle passing f64 on LA32D with a soft float ABI or when floating point
10613 // registers are exhausted.
10614 assert(PendingLocs.empty() && "Can't lower f64 if it is split");
10615 // Depending on available argument GPRS, f64 may be passed in a pair of
10616 // GPRs, split between a GPR and the stack, or passed completely on the
10617 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10618 // cases.
10619 MCRegister Reg = allocateArgGPR(State);
10620 if (!Reg) {
10621 int64_t StackOffset = State.AllocateStack(8, Align(8));
10622 State.addLoc(
10623 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10624 return false;
10625 }
10626 LocVT = MVT::i32;
10627 State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10628 MCRegister HiReg = allocateArgGPR(State);
10629 if (HiReg) {
10630 State.addLoc(
10631 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
10632 } else {
10633 int64_t StackOffset = State.AllocateStack(4, Align(4));
10634 State.addLoc(
10635 CCValAssign::getCustomMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10636 }
10637 return false;
10638 }
10639
10640 // Split arguments might be passed indirectly, so keep track of the pending
10641 // values.
10642 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10643 LocVT = GRLenVT;
10644 LocInfo = CCValAssign::Indirect;
10645 PendingLocs.push_back(
10646 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10647 PendingArgFlags.push_back(ArgFlags);
10648 if (!ArgFlags.isSplitEnd()) {
10649 return false;
10650 }
10651 }
10652
10653 // If the split argument only had two elements, it should be passed directly
10654 // in registers or on the stack.
10655 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10656 PendingLocs.size() <= 2) {
10657 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10658 // Apply the normal calling convention rules to the first half of the
10659 // split argument.
10660 CCValAssign VA = PendingLocs[0];
10661 ISD::ArgFlagsTy AF = PendingArgFlags[0];
10662 PendingLocs.clear();
10663 PendingArgFlags.clear();
10664 return CC_LoongArchAssign2GRLen(GRLen, State, VA, AF, ValNo, ValVT, LocVT,
10665 ArgFlags);
10666 }
10667
10668 // Allocate to a register if possible, or else a stack slot.
10669 Register Reg;
10670 unsigned StoreSizeBytes = GRLen / 8;
10671 Align StackAlign = Align(GRLen / 8);
10672
10673 if (ValVT == MVT::f32 && !UseGPRForFloat) {
10674 Reg = State.AllocateReg(ArgFPR32s);
10675 } else if (ValVT == MVT::f64 && !UseGPRForFloat) {
10676 Reg = State.AllocateReg(ArgFPR64s);
10677 } else if (ValVT.is128BitVector()) {
10678 Reg = State.AllocateReg(ArgVRs);
10679 UseGPRForFloat = false;
10680 StoreSizeBytes = 16;
10681 StackAlign = Align(16);
10682 } else if (ValVT.is256BitVector()) {
10683 Reg = State.AllocateReg(ArgXRs);
10684 UseGPRForFloat = false;
10685 StoreSizeBytes = 32;
10686 StackAlign = Align(32);
10687 } else {
10688 Reg = allocateArgGPR(State);
10689 }
10690
10691 unsigned StackOffset =
10692 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10693
10694 // If we reach this point and PendingLocs is non-empty, we must be at the
10695 // end of a split argument that must be passed indirectly.
10696 if (!PendingLocs.empty()) {
10697 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10698 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10699 for (auto &It : PendingLocs) {
10700 if (Reg)
10701 It.convertToReg(Reg);
10702 else
10703 It.convertToMem(StackOffset);
10704 State.addLoc(It);
10705 }
10706 PendingLocs.clear();
10707 PendingArgFlags.clear();
10708 return false;
10709 }
10710 assert((!UseGPRForFloat || LocVT == GRLenVT) &&
10711 "Expected an GRLenVT at this stage");
10712
10713 if (Reg) {
10714 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10715 return false;
10716 }
10717
10718 // When a floating-point value is passed on the stack, no bit-cast is needed.
10719 if (ValVT.isFloatingPoint()) {
10720 LocVT = ValVT;
10721 LocInfo = CCValAssign::Full;
10722 }
10723
10724 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10725 return false;
10726}
10727
10728void LoongArchTargetLowering::analyzeInputArgs(
10729 MachineFunction &MF, CCState &CCInfo,
10730 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10731 LoongArchCCAssignFn Fn) const {
10732 FunctionType *FType = MF.getFunction().getFunctionType();
10733 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10734 MVT ArgVT = Ins[i].VT;
10735 Type *ArgTy = nullptr;
10736 if (IsRet)
10737 ArgTy = FType->getReturnType();
10738 else if (Ins[i].isOrigArg())
10739 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10741 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
10742 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, CCValAssign::Full, Ins[i].Flags,
10743 CCInfo, IsRet, ArgTy)) {
10744 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " << ArgVT
10745 << '\n');
10746 llvm_unreachable("");
10747 }
10748 }
10749}
10750
10751void LoongArchTargetLowering::analyzeOutputArgs(
10752 MachineFunction &MF, CCState &CCInfo,
10753 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10754 CallLoweringInfo *CLI, LoongArchCCAssignFn Fn) const {
10755 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10756 MVT ArgVT = Outs[i].VT;
10757 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10759 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
10760 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, CCValAssign::Full, Outs[i].Flags,
10761 CCInfo, IsRet, OrigTy)) {
10762 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " << ArgVT
10763 << "\n");
10764 llvm_unreachable("");
10765 }
10766 }
10767}
10768
10769// Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10770// values.
10772 const CCValAssign &VA, const SDLoc &DL) {
10773 switch (VA.getLocInfo()) {
10774 default:
10775 llvm_unreachable("Unexpected CCValAssign::LocInfo");
10776 case CCValAssign::Full:
10778 break;
10779 case CCValAssign::BCvt:
10780 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10781 Val = DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, Val);
10782 else
10783 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10784 break;
10785 }
10786 return Val;
10787}
10788
10790 const CCValAssign &VA, const SDLoc &DL,
10791 const ISD::InputArg &In,
10795 EVT LocVT = VA.getLocVT();
10796 SDValue Val;
10797 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10798 Register VReg = RegInfo.createVirtualRegister(RC);
10799 RegInfo.addLiveIn(VA.getLocReg(), VReg);
10800 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10801
10802 // If input is sign extended from 32 bits, note it for the OptW pass.
10803 if (In.isOrigArg()) {
10804 Argument *OrigArg = MF.getFunction().getArg(In.getOrigArgIndex());
10805 if (OrigArg->getType()->isIntegerTy()) {
10806 unsigned BitWidth = OrigArg->getType()->getIntegerBitWidth();
10807 // An input zero extended from i31 can also be considered sign extended.
10808 if ((BitWidth <= 32 && In.Flags.isSExt()) ||
10809 (BitWidth < 32 && In.Flags.isZExt())) {
10812 LAFI->addSExt32Register(VReg);
10813 }
10814 }
10815 }
10816
10817 return convertLocVTToValVT(DAG, Val, VA, DL);
10818}
10819
10820// The caller is responsible for loading the full value if the argument is
10821// passed with CCValAssign::Indirect.
10823 const CCValAssign &VA, const SDLoc &DL) {
10825 MachineFrameInfo &MFI = MF.getFrameInfo();
10826 EVT ValVT = VA.getValVT();
10827 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10828 /*IsImmutable=*/true);
10829 SDValue FIN = DAG.getFrameIndex(
10831
10832 ISD::LoadExtType ExtType;
10833 switch (VA.getLocInfo()) {
10834 default:
10835 llvm_unreachable("Unexpected CCValAssign::LocInfo");
10836 case CCValAssign::Full:
10838 case CCValAssign::BCvt:
10839 ExtType = ISD::NON_EXTLOAD;
10840 break;
10841 }
10842 return DAG.getExtLoad(
10843 ExtType, DL, VA.getLocVT(), Chain, FIN,
10845}
10846
10848 const CCValAssign &VA,
10849 const CCValAssign &HiVA,
10850 const SDLoc &DL) {
10851 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10852 "Unexpected VA");
10854 MachineFrameInfo &MFI = MF.getFrameInfo();
10856
10857 assert(VA.isRegLoc() && "Expected register VA assignment");
10858
10859 Register LoVReg = RegInfo.createVirtualRegister(&LoongArch::GPRRegClass);
10860 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10861 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10862 SDValue Hi;
10863 if (HiVA.isMemLoc()) {
10864 // Second half of f64 is passed on the stack.
10865 int FI = MFI.CreateFixedObject(4, HiVA.getLocMemOffset(),
10866 /*IsImmutable=*/true);
10867 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10868 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10870 } else {
10871 // Second half of f64 is passed in another GPR.
10872 Register HiVReg = RegInfo.createVirtualRegister(&LoongArch::GPRRegClass);
10873 RegInfo.addLiveIn(HiVA.getLocReg(), HiVReg);
10874 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10875 }
10876 return DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64, Lo, Hi);
10877}
10878
10880 const CCValAssign &VA, const SDLoc &DL) {
10881 EVT LocVT = VA.getLocVT();
10882
10883 switch (VA.getLocInfo()) {
10884 default:
10885 llvm_unreachable("Unexpected CCValAssign::LocInfo");
10886 case CCValAssign::Full:
10887 break;
10888 case CCValAssign::BCvt:
10889 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10890 Val = DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Val);
10891 else
10892 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10893 break;
10894 }
10895 return Val;
10896}
10897
10898static bool CC_LoongArch_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10899 CCValAssign::LocInfo LocInfo,
10900 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
10901 CCState &State) {
10902 if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10903 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, SpLim
10904 // s0 s1 s2 s3 s4 s5 s6 s7 s8
10905 static const MCPhysReg GPRList[] = {
10906 LoongArch::R23, LoongArch::R24, LoongArch::R25,
10907 LoongArch::R26, LoongArch::R27, LoongArch::R28,
10908 LoongArch::R29, LoongArch::R30, LoongArch::R31};
10909 if (MCRegister Reg = State.AllocateReg(GPRList)) {
10910 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10911 return false;
10912 }
10913 }
10914
10915 if (LocVT == MVT::f32) {
10916 // Pass in STG registers: F1, F2, F3, F4
10917 // fs0,fs1,fs2,fs3
10918 static const MCPhysReg FPR32List[] = {LoongArch::F24, LoongArch::F25,
10919 LoongArch::F26, LoongArch::F27};
10920 if (MCRegister Reg = State.AllocateReg(FPR32List)) {
10921 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10922 return false;
10923 }
10924 }
10925
10926 if (LocVT == MVT::f64) {
10927 // Pass in STG registers: D1, D2, D3, D4
10928 // fs4,fs5,fs6,fs7
10929 static const MCPhysReg FPR64List[] = {LoongArch::F28_64, LoongArch::F29_64,
10930 LoongArch::F30_64, LoongArch::F31_64};
10931 if (MCRegister Reg = State.AllocateReg(FPR64List)) {
10932 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10933 return false;
10934 }
10935 }
10936
10937 report_fatal_error("No registers left in GHC calling convention");
10938 return true;
10939}
10940
10941// Transform physical registers into virtual registers.
10943 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10944 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10945 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10946
10948
10949 switch (CallConv) {
10950 default:
10951 llvm_unreachable("Unsupported calling convention");
10952 case CallingConv::C:
10953 case CallingConv::Fast:
10956 break;
10957 case CallingConv::GHC:
10958 if (!MF.getSubtarget().hasFeature(LoongArch::FeatureBasicF) ||
10959 !MF.getSubtarget().hasFeature(LoongArch::FeatureBasicD))
10961 "GHC calling convention requires the F and D extensions");
10962 }
10963
10964 const Function &Func = MF.getFunction();
10965 EVT PtrVT = getPointerTy(DAG.getDataLayout());
10966 MVT GRLenVT = Subtarget.getGRLenVT();
10967 unsigned GRLenInBytes = Subtarget.getGRLen() / 8;
10968
10969 // Check if this function has any musttail calls. If so, incoming indirect
10970 // arg pointers must be saved in virtual registers so they survive across
10971 // basic blocks (the SelectionDAG is cleared between BBs). Only do this
10972 // when needed to avoid adding register pressure to non-musttail functions.
10973 bool HasMusttail = llvm::any_of(Func, [](const BasicBlock &BB) {
10974 return llvm::any_of(BB, [](const Instruction &I) {
10975 if (const auto *CI = dyn_cast<CallInst>(&I))
10976 return CI->isMustTailCall();
10977 return false;
10978 });
10979 });
10980 // Used with varargs to acumulate store chains.
10981 std::vector<SDValue> OutChains;
10982
10983 // Assign locations to all of the incoming arguments.
10985 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10986
10987 if (CallConv == CallingConv::GHC)
10989 else
10990 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, CC_LoongArch);
10991
10992 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
10993 CCValAssign &VA = ArgLocs[i];
10994 SDValue ArgValue;
10995 // Passing f64 on LA32D with a soft float ABI must be handled as a special
10996 // case.
10997 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10998 assert(VA.needsCustom());
10999 ArgValue = unpackF64OnLA32DSoftABI(DAG, Chain, VA, ArgLocs[++i], DL);
11000 } else if (VA.isRegLoc())
11001 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, Ins[InsIdx], *this);
11002 else
11003 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
11004 if (VA.getLocInfo() == CCValAssign::Indirect) {
11005 // If the original argument was split and passed by reference, we need to
11006 // load all parts of it here (using the same address).
11007 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
11009 unsigned ArgIndex = Ins[InsIdx].OrigArgIndex;
11010 if (HasMusttail) {
11013 Register VReg =
11014 MF.getRegInfo().createVirtualRegister(&LoongArch::GPRRegClass);
11015 Chain = DAG.getCopyToReg(Chain, DL, VReg, ArgValue);
11016 LAFI->setIncomingIndirectArg(ArgIndex, VReg);
11017 }
11018 unsigned ArgPartOffset = Ins[InsIdx].PartOffset;
11019 assert(ArgPartOffset == 0);
11020 while (i + 1 != e && Ins[InsIdx + 1].OrigArgIndex == ArgIndex) {
11021 CCValAssign &PartVA = ArgLocs[i + 1];
11022 unsigned PartOffset = Ins[InsIdx + 1].PartOffset - ArgPartOffset;
11023 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11024 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
11025 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
11027 ++i;
11028 ++InsIdx;
11029 }
11030 continue;
11031 }
11032 InVals.push_back(ArgValue);
11033 }
11034
11035 if (IsVarArg) {
11037 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
11038 const TargetRegisterClass *RC = &LoongArch::GPRRegClass;
11039 MachineFrameInfo &MFI = MF.getFrameInfo();
11040 MachineRegisterInfo &RegInfo = MF.getRegInfo();
11041 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
11042
11043 // Offset of the first variable argument from stack pointer, and size of
11044 // the vararg save area. For now, the varargs save area is either zero or
11045 // large enough to hold a0-a7.
11046 int VaArgOffset, VarArgsSaveSize;
11047
11048 // If all registers are allocated, then all varargs must be passed on the
11049 // stack and we don't need to save any argregs.
11050 if (ArgRegs.size() == Idx) {
11051 VaArgOffset = CCInfo.getStackSize();
11052 VarArgsSaveSize = 0;
11053 } else {
11054 VarArgsSaveSize = GRLenInBytes * (ArgRegs.size() - Idx);
11055 VaArgOffset = -VarArgsSaveSize;
11056 }
11057
11058 // Record the frame index of the first variable argument
11059 // which is a value necessary to VASTART.
11060 int FI = MFI.CreateFixedObject(GRLenInBytes, VaArgOffset, true);
11061 LoongArchFI->setVarArgsFrameIndex(FI);
11062
11063 // If saving an odd number of registers then create an extra stack slot to
11064 // ensure that the frame pointer is 2*GRLen-aligned, which in turn ensures
11065 // offsets to even-numbered registered remain 2*GRLen-aligned.
11066 if (Idx % 2) {
11067 MFI.CreateFixedObject(GRLenInBytes, VaArgOffset - (int)GRLenInBytes,
11068 true);
11069 VarArgsSaveSize += GRLenInBytes;
11070 }
11071
11072 // Copy the integer registers that may have been used for passing varargs
11073 // to the vararg save area.
11074 for (unsigned I = Idx; I < ArgRegs.size();
11075 ++I, VaArgOffset += GRLenInBytes) {
11076 const Register Reg = RegInfo.createVirtualRegister(RC);
11077 RegInfo.addLiveIn(ArgRegs[I], Reg);
11078 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, GRLenVT);
11079 FI = MFI.CreateFixedObject(GRLenInBytes, VaArgOffset, true);
11080 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11081 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
11083 cast<StoreSDNode>(Store.getNode())
11084 ->getMemOperand()
11085 ->setValue((Value *)nullptr);
11086 OutChains.push_back(Store);
11087 }
11088 LoongArchFI->setVarArgsSaveSize(VarArgsSaveSize);
11089 }
11090
11091 // All stores are grouped in one node to allow the matching between
11092 // the size of Ins and InVals. This only happens for vararg functions.
11093 if (!OutChains.empty()) {
11094 OutChains.push_back(Chain);
11095 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
11096 }
11097
11098 return Chain;
11099}
11100
11102 return CI->isTailCall();
11103}
11104
11105// Check if the return value is used as only a return value, as otherwise
11106// we can't perform a tail-call.
11108 SDValue &Chain) const {
11109 if (N->getNumValues() != 1)
11110 return false;
11111 if (!N->hasNUsesOfValue(1, 0))
11112 return false;
11113
11114 SDNode *Copy = *N->user_begin();
11115 if (Copy->getOpcode() != ISD::CopyToReg)
11116 return false;
11117
11118 // If the ISD::CopyToReg has a glue operand, we conservatively assume it
11119 // isn't safe to perform a tail call.
11120 if (Copy->getGluedNode())
11121 return false;
11122
11123 // The copy must be used by a LoongArchISD::RET, and nothing else.
11124 bool HasRet = false;
11125 for (SDNode *Node : Copy->users()) {
11126 if (Node->getOpcode() != LoongArchISD::RET)
11127 return false;
11128 HasRet = true;
11129 }
11130
11131 if (!HasRet)
11132 return false;
11133
11134 Chain = Copy->getOperand(0);
11135 return true;
11136}
11137
11138// Check whether the call is eligible for tail call optimization.
11139bool LoongArchTargetLowering::isEligibleForTailCallOptimization(
11140 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
11141 const SmallVectorImpl<CCValAssign> &ArgLocs) const {
11142
11143 auto CalleeCC = CLI.CallConv;
11144 auto &Outs = CLI.Outs;
11145 auto &Caller = MF.getFunction();
11146 auto CallerCC = Caller.getCallingConv();
11147
11148 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
11149
11150 // Byval parameters hand the function a pointer directly into the stack area
11151 // we want to reuse during a tail call. Working around this *is* possible
11152 // but less efficient and uglier in LowerCall. For musttail, there is no
11153 // workaround today: a byval arg requires a local copy that becomes invalid
11154 // after the tail call deallocates the caller's frame, so rejecting here
11155 // (and triggering reportFatalInternalError in LowerCall) is safer than
11156 // miscompiling.
11157 for (auto &Arg : Outs)
11158 if (Arg.Flags.isByVal())
11159 return false;
11160
11161 // musttail bypasses the remaining checks: the checks either reject cases
11162 // we handle specially (indirect args are forwarded via incoming pointers,
11163 // stack-passed args reuse the matching incoming layout, sret is forwarded
11164 // like any other pointer arg) or are optimizations not applicable to
11165 // mandatory tail calls.
11166 if (IsMustTail)
11167 return true;
11168
11169 // Do not tail call opt if the stack is used to pass parameters.
11170 if (CCInfo.getStackSize() != 0)
11171 return false;
11172
11173 // Do not tail call opt if any parameters need to be passed indirectly.
11174 for (auto &VA : ArgLocs)
11175 if (VA.getLocInfo() == CCValAssign::Indirect)
11176 return false;
11177
11178 // Do not tail call opt if either caller or callee uses struct return
11179 // semantics.
11180 auto IsCallerStructRet = Caller.hasStructRetAttr();
11181 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
11182 if (IsCallerStructRet || IsCalleeStructRet)
11183 return false;
11184
11185 // The callee has to preserve all registers the caller needs to preserve.
11186 const LoongArchRegisterInfo *TRI = Subtarget.getRegisterInfo();
11187 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
11188 if (CalleeCC != CallerCC) {
11189 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
11190 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
11191 return false;
11192 }
11193 return true;
11194}
11195
11197 return DAG.getDataLayout().getPrefTypeAlign(
11198 VT.getTypeForEVT(*DAG.getContext()));
11199}
11200
11201// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
11202// and output parameter nodes.
11203SDValue
11205 SmallVectorImpl<SDValue> &InVals) const {
11206 SelectionDAG &DAG = CLI.DAG;
11207 SDLoc &DL = CLI.DL;
11209 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
11211 SDValue Chain = CLI.Chain;
11212 SDValue Callee = CLI.Callee;
11213 CallingConv::ID CallConv = CLI.CallConv;
11214 bool IsVarArg = CLI.IsVarArg;
11215 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11216 MVT GRLenVT = Subtarget.getGRLenVT();
11217 bool &IsTailCall = CLI.IsTailCall;
11218
11220
11221 // Analyze the operands of the call, assigning locations to each operand.
11223 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11224
11225 if (CallConv == CallingConv::GHC)
11226 ArgCCInfo.AnalyzeCallOperands(Outs, CC_LoongArch_GHC);
11227 else
11228 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, CC_LoongArch);
11229
11230 // Check if it's really possible to do a tail call.
11231 if (IsTailCall)
11232 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
11233
11234 if (IsTailCall)
11235 ++NumTailCalls;
11236 else if (CLI.CB && CLI.CB->isMustTailCall())
11237 report_fatal_error("failed to perform tail call elimination on a call "
11238 "site marked musttail");
11239
11240 // Get a count of how many bytes are to be pushed on the stack.
11241 unsigned NumBytes = ArgCCInfo.getStackSize();
11242
11243 // Create local copies for byval args.
11244 SmallVector<SDValue> ByValArgs;
11245 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11246 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11247 if (!Flags.isByVal())
11248 continue;
11249
11250 SDValue Arg = OutVals[i];
11251 unsigned Size = Flags.getByValSize();
11252 Align Alignment = Flags.getNonZeroByValAlign();
11253
11254 int FI =
11255 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
11256 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11257 SDValue SizeNode = DAG.getConstant(Size, DL, GRLenVT);
11258
11259 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, Alignment,
11260 /*IsVolatile=*/false,
11261 /*AlwaysInline=*/false, /*CI=*/nullptr, std::nullopt,
11263 ByValArgs.push_back(FIPtr);
11264 }
11265
11266 if (!IsTailCall)
11267 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
11268
11269 // Copy argument values to their designated locations.
11271 SmallVector<SDValue> MemOpChains;
11272 SDValue StackPtr;
11273 for (unsigned i = 0, j = 0, e = ArgLocs.size(), OutIdx = 0; i != e;
11274 ++i, ++OutIdx) {
11275 CCValAssign &VA = ArgLocs[i];
11276 SDValue ArgValue = OutVals[OutIdx];
11277 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
11278
11279 // Handle passing f64 on LA32D with a soft float ABI as a special case.
11280 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11281 assert(VA.isRegLoc() && "Expected register VA assignment");
11282 assert(VA.needsCustom());
11283 SDValue SplitF64 =
11284 DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
11285 DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11286 SDValue Lo = SplitF64.getValue(0);
11287 SDValue Hi = SplitF64.getValue(1);
11288
11289 Register RegLo = VA.getLocReg();
11290 RegsToPass.push_back(std::make_pair(RegLo, Lo));
11291
11292 // Get the CCValAssign for the Hi part.
11293 CCValAssign &HiVA = ArgLocs[++i];
11294
11295 if (HiVA.isMemLoc()) {
11296 // Second half of f64 is passed on the stack.
11297 if (!StackPtr.getNode())
11298 StackPtr = DAG.getCopyFromReg(Chain, DL, LoongArch::R3, PtrVT);
11300 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11301 DAG.getIntPtrConstant(HiVA.getLocMemOffset(), DL));
11302 // Emit the store.
11303 MemOpChains.push_back(DAG.getStore(
11304 Chain, DL, Hi, Address,
11306 } else {
11307 // Second half of f64 is passed in another GPR.
11308 Register RegHigh = HiVA.getLocReg();
11309 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11310 }
11311 continue;
11312 }
11313
11314 // Promote the value if needed.
11315 // For now, only handle fully promoted and indirect arguments.
11316 if (VA.getLocInfo() == CCValAssign::Indirect) {
11317 // For musttail calls, reuse incoming indirect pointers instead of
11318 // creating new stack temporaries. The incoming pointers point to the
11319 // caller's caller's frame, which remains valid after a tail call.
11320 if (IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
11323 unsigned CallArgIdx = Outs[OutIdx].OrigArgIndex;
11324
11325 // Resolve which formal parameter is being passed at this call
11326 // position.
11327 //
11328 // FIXME: Ins[].OrigArgIndex is Argument::getArgNo() (unfiltered),
11329 // but Outs[].OrigArgIndex is an index into a filtered arg list
11330 // (empty types removed, via CallLoweringInfo in the target-
11331 // independent layer). IncomingIndirectArgs is keyed by the
11332 // caller's unfiltered Argument::getArgNo(), so we have to walk
11333 // the caller's formals (same filter) to translate the index.
11334 // This target-independent asymmetry should be normalized so
11335 // backends do not need to re-derive the mapping.
11336 //
11337 // Steps:
11338 // 1. Find the call operand at filtered position CallArgIdx.
11339 // 2. If it is an Argument, use getArgNo() directly (same filter
11340 // for caller formals and call operands).
11341 // 3. Otherwise (computed value), walk the caller's formals and
11342 // skip empty types to map the filtered index to getArgNo().
11343 const Argument *FormalArg = nullptr;
11344 unsigned FilteredIdx = 0;
11345 for (const auto &CallArg : CLI.CB->args()) {
11346 if (CallArg->getType()->isEmptyTy())
11347 continue;
11348 if (FilteredIdx == CallArgIdx) {
11349 FormalArg = dyn_cast<Argument>(CallArg);
11350 break;
11351 }
11352 ++FilteredIdx;
11353 }
11354
11355 // For forwarded args, getArgNo() gives the unfiltered index directly.
11356 // For computed args, walk the caller's formals to resolve it.
11357 unsigned FormalArgIdx = CallArgIdx;
11358 if (FormalArg) {
11359 FormalArgIdx = FormalArg->getArgNo();
11360 } else {
11361 FilteredIdx = 0;
11362 for (const auto &Arg : MF.getFunction().args()) {
11363 if (Arg.getType()->isEmptyTy())
11364 continue;
11365 if (FilteredIdx == CallArgIdx) {
11366 FormalArgIdx = Arg.getArgNo();
11367 break;
11368 }
11369 ++FilteredIdx;
11370 }
11371 }
11372
11373 Register VReg = LAFI->getIncomingIndirectArg(FormalArgIdx);
11374 SDValue CopyOp = DAG.getCopyFromReg(Chain, DL, VReg, PtrVT);
11375 // Thread the CopyFromReg output chain through MemOpChains so the
11376 // TokenFactor below sequences the copy with any stores we emit
11377 // for this argument.
11378 MemOpChains.push_back(CopyOp.getValue(1));
11379 SDValue IncomingPtr = CopyOp;
11380
11381 if (!FormalArg) {
11382 // Computed value: store into the incoming indirect pointer for the
11383 // same-position formal parameter (musttail guarantees matching
11384 // prototypes, so types match). The pointer survives the tail call
11385 // since it points to the caller's caller's frame.
11386 //
11387 // The data-flow edge through IncomingPtr already prevents the
11388 // store from being scheduled before the CopyFromReg. Threading
11389 // CopyOp.getValue(1) (the copy's output chain) into the store
11390 // makes that ordering explicit on the chain edge as well, which
11391 // is the convention for memory ops chaining off their producers.
11392 MemOpChains.push_back(
11393 DAG.getStore(CopyOp.getValue(1), DL, ArgValue, IncomingPtr,
11395 // Store any split parts at their respective offsets.
11396 unsigned ArgPartOffset = Outs[OutIdx].PartOffset;
11397 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == CallArgIdx) {
11398 SDValue PartValue = OutVals[OutIdx + 1];
11399 unsigned PartOffset = Outs[OutIdx + 1].PartOffset - ArgPartOffset;
11400 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11401 SDValue Addr =
11402 DAG.getNode(ISD::ADD, DL, PtrVT, IncomingPtr, Offset);
11403 MemOpChains.push_back(
11404 DAG.getStore(CopyOp.getValue(1), DL, PartValue, Addr,
11406 ++i;
11407 ++OutIdx;
11408 }
11409 }
11410 ArgValue = IncomingPtr;
11411
11412 // Skip any remaining split parts (for forwarded args, they are
11413 // covered by the forwarded pointer).
11414 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == CallArgIdx) {
11415 ++i;
11416 ++OutIdx;
11417 }
11418 } else {
11419 // Store the argument in a stack slot and pass its address.
11420 Align StackAlign =
11421 std::max(getPrefTypeAlign(Outs[OutIdx].ArgVT, DAG),
11422 getPrefTypeAlign(ArgValue.getValueType(), DAG));
11423 TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11424 // If the original argument was split and passed by reference, we need
11425 // to store the required parts of it here (and pass just one address).
11426 unsigned ArgIndex = Outs[OutIdx].OrigArgIndex;
11427 unsigned ArgPartOffset = Outs[OutIdx].PartOffset;
11428 assert(ArgPartOffset == 0);
11429 // Calculate the total size to store. We don't have access to what we're
11430 // actually storing other than performing the loop and collecting the
11431 // info.
11433 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == ArgIndex) {
11434 SDValue PartValue = OutVals[OutIdx + 1];
11435 unsigned PartOffset = Outs[OutIdx + 1].PartOffset - ArgPartOffset;
11436 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11437 EVT PartVT = PartValue.getValueType();
11438 StoredSize += PartVT.getStoreSize();
11439 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11440 Parts.push_back(std::make_pair(PartValue, Offset));
11441 ++i;
11442 ++OutIdx;
11443 }
11444 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11445 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11446 MemOpChains.push_back(
11447 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11449 for (const auto &Part : Parts) {
11450 SDValue PartValue = Part.first;
11451 SDValue PartOffset = Part.second;
11453 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11454 MemOpChains.push_back(
11455 DAG.getStore(Chain, DL, PartValue, Address,
11457 }
11458 ArgValue = SpillSlot;
11459 }
11460 } else {
11461 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
11462 }
11463
11464 // Use local copy if it is a byval arg.
11465 if (Flags.isByVal())
11466 ArgValue = ByValArgs[j++];
11467
11468 if (VA.isRegLoc()) {
11469 // Queue up the argument copies and emit them at the end.
11470 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11471 } else {
11472 assert(VA.isMemLoc() && "Argument not register or memory");
11473 assert((!IsTailCall || (CLI.CB && CLI.CB->isMustTailCall())) &&
11474 "Tail call not allowed if stack is used for passing parameters");
11475
11476 // Work out the address of the stack slot.
11477 if (!StackPtr.getNode())
11478 StackPtr = DAG.getCopyFromReg(Chain, DL, LoongArch::R3, PtrVT);
11480 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11482
11483 // Emit the store.
11484 MemOpChains.push_back(
11485 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11486 }
11487 }
11488
11489 // Join the stores, which are independent of one another.
11490 if (!MemOpChains.empty())
11491 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11492
11493 SDValue Glue;
11494
11495 // Build a sequence of copy-to-reg nodes, chained and glued together.
11496 for (auto &Reg : RegsToPass) {
11497 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11498 Glue = Chain.getValue(1);
11499 }
11500
11501 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11502 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11503 // split it and then direct call can be matched by PseudoCALL_SMALL.
11505 const GlobalValue *GV = S->getGlobal();
11506 unsigned OpFlags = getTargetMachine().shouldAssumeDSOLocal(GV)
11509 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, OpFlags);
11510 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11511 unsigned OpFlags = getTargetMachine().shouldAssumeDSOLocal(nullptr)
11514 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11515 }
11516
11517 // The first call operand is the chain and the second is the target address.
11519 Ops.push_back(Chain);
11520 Ops.push_back(Callee);
11521
11522 // Add argument registers to the end of the list so that they are
11523 // known live into the call.
11524 for (auto &Reg : RegsToPass)
11525 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11526
11527 if (!IsTailCall) {
11528 // Add a register mask operand representing the call-preserved registers.
11529 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11530 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11531 assert(Mask && "Missing call preserved mask for calling convention");
11532 Ops.push_back(DAG.getRegisterMask(Mask));
11533 }
11534
11535 // Glue the call to the argument copies, if any.
11536 if (Glue.getNode())
11537 Ops.push_back(Glue);
11538
11539 // Emit the call.
11540 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11541 unsigned Op;
11542 switch (DAG.getTarget().getCodeModel()) {
11543 default:
11544 report_fatal_error("Unsupported code model");
11545 case CodeModel::Small:
11546 Op = IsTailCall ? LoongArchISD::TAIL : LoongArchISD::CALL;
11547 break;
11548 case CodeModel::Medium:
11549 Op = IsTailCall ? LoongArchISD::TAIL_MEDIUM : LoongArchISD::CALL_MEDIUM;
11550 break;
11551 case CodeModel::Large:
11552 assert(Subtarget.is64Bit() && "Large code model requires LA64");
11553 Op = IsTailCall ? LoongArchISD::TAIL_LARGE : LoongArchISD::CALL_LARGE;
11554 break;
11555 }
11556
11557 if (IsTailCall) {
11559 SDValue Ret = DAG.getNode(Op, DL, NodeTys, Ops);
11560 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
11561 return Ret;
11562 }
11563
11564 Chain = DAG.getNode(Op, DL, NodeTys, Ops);
11565 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11566 Glue = Chain.getValue(1);
11567
11568 // Mark the end of the call, which is glued to the call itself.
11569 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
11570 Glue = Chain.getValue(1);
11571
11572 // Assign locations to each value returned by this call.
11574 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11575 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_LoongArch);
11576
11577 // Copy all of the result registers out of their specified physreg.
11578 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
11579 auto &VA = RVLocs[i];
11580 // Copy the value out.
11581 SDValue RetValue =
11582 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11583 // Glue the RetValue to the end of the call sequence.
11584 Chain = RetValue.getValue(1);
11585 Glue = RetValue.getValue(2);
11586
11587 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11588 assert(VA.needsCustom());
11589 SDValue RetValue2 = DAG.getCopyFromReg(Chain, DL, RVLocs[++i].getLocReg(),
11590 MVT::i32, Glue);
11591 Chain = RetValue2.getValue(1);
11592 Glue = RetValue2.getValue(2);
11593 RetValue = DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64,
11594 RetValue, RetValue2);
11595 } else
11596 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
11597
11598 InVals.push_back(RetValue);
11599 }
11600
11601 return Chain;
11602}
11603
11605 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11606 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
11607 const Type *RetTy) const {
11609 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11610
11611 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11612 LoongArchABI::ABI ABI =
11613 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
11614 if (CC_LoongArch(MF.getDataLayout(), ABI, i, Outs[i].VT, CCValAssign::Full,
11615 Outs[i].Flags, CCInfo, /*IsRet=*/true, nullptr))
11616 return false;
11617 }
11618 return true;
11619}
11620
11622 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
11624 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
11625 SelectionDAG &DAG) const {
11626 // Stores the assignment of the return value to a location.
11628
11629 // Info about the registers and stack slot.
11630 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11631 *DAG.getContext());
11632
11633 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11634 nullptr, CC_LoongArch);
11635 if (CallConv == CallingConv::GHC && !RVLocs.empty())
11636 report_fatal_error("GHC functions return void only");
11637 SDValue Glue;
11638 SmallVector<SDValue, 4> RetOps(1, Chain);
11639
11640 // Copy the result values into the output registers.
11641 for (unsigned i = 0, e = RVLocs.size(), OutIdx = 0; i < e; ++i, ++OutIdx) {
11642 SDValue Val = OutVals[OutIdx];
11643 CCValAssign &VA = RVLocs[i];
11644 assert(VA.isRegLoc() && "Can only return in registers!");
11645
11646 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11647 // Handle returning f64 on LA32D with a soft float ABI.
11648 assert(VA.isRegLoc() && "Expected return via registers");
11649 assert(VA.needsCustom());
11650 SDValue SplitF64 = DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
11651 DAG.getVTList(MVT::i32, MVT::i32), Val);
11652 SDValue Lo = SplitF64.getValue(0);
11653 SDValue Hi = SplitF64.getValue(1);
11654 Register RegLo = VA.getLocReg();
11655 Register RegHi = RVLocs[++i].getLocReg();
11656
11657 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11658 Glue = Chain.getValue(1);
11659 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11660 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11661 Glue = Chain.getValue(1);
11662 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11663 } else {
11664 // Handle a 'normal' return.
11665 Val = convertValVTToLocVT(DAG, Val, VA, DL);
11666 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11667
11668 // Guarantee that all emitted copies are stuck together.
11669 Glue = Chain.getValue(1);
11670 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11671 }
11672 }
11673
11674 RetOps[0] = Chain; // Update chain.
11675
11676 // Add the glue node if we have it.
11677 if (Glue.getNode())
11678 RetOps.push_back(Glue);
11679
11680 return DAG.getNode(LoongArchISD::RET, DL, MVT::Other, RetOps);
11681}
11682
11683// Check if a constant splat can be generated using [x]vldi, where imm[12] == 1.
11684// Note: The following prefixes are excluded:
11685// imm[11:8] == 4'b0000, 4'b0100, 4'b1000
11686// as they can be represented using [x]vrepli.[whb]
11688 const APInt &SplatValue, const unsigned SplatBitSize) const {
11689 uint64_t RequiredImm = 0;
11690 uint64_t V = SplatValue.getZExtValue();
11691 if (SplatBitSize == 16 && !(V & 0x00FF)) {
11692 // 4'b0101
11693 RequiredImm = (0b10101 << 8) | (V >> 8);
11694 return {true, RequiredImm};
11695 } else if (SplatBitSize == 32) {
11696 // 4'b0001
11697 if (!(V & 0xFFFF00FF)) {
11698 RequiredImm = (0b10001 << 8) | (V >> 8);
11699 return {true, RequiredImm};
11700 }
11701 // 4'b0010
11702 if (!(V & 0xFF00FFFF)) {
11703 RequiredImm = (0b10010 << 8) | (V >> 16);
11704 return {true, RequiredImm};
11705 }
11706 // 4'b0011
11707 if (!(V & 0x00FFFFFF)) {
11708 RequiredImm = (0b10011 << 8) | (V >> 24);
11709 return {true, RequiredImm};
11710 }
11711 // 4'b0110
11712 if ((V & 0xFFFF00FF) == 0xFF) {
11713 RequiredImm = (0b10110 << 8) | (V >> 8);
11714 return {true, RequiredImm};
11715 }
11716 // 4'b0111
11717 if ((V & 0xFF00FFFF) == 0xFFFF) {
11718 RequiredImm = (0b10111 << 8) | (V >> 16);
11719 return {true, RequiredImm};
11720 }
11721 // 4'b1010
11722 if ((V & 0x7E07FFFF) == 0x3E000000 || (V & 0x7E07FFFF) == 0x40000000) {
11723 RequiredImm =
11724 (0b11010 << 8) | (((V >> 24) & 0xC0) ^ 0x40) | ((V >> 19) & 0x3F);
11725 return {true, RequiredImm};
11726 }
11727 } else if (SplatBitSize == 64) {
11728 // 4'b1011
11729 if ((V & 0xFFFFFFFF7E07FFFFULL) == 0x3E000000ULL ||
11730 (V & 0xFFFFFFFF7E07FFFFULL) == 0x40000000ULL) {
11731 RequiredImm =
11732 (0b11011 << 8) | (((V >> 24) & 0xC0) ^ 0x40) | ((V >> 19) & 0x3F);
11733 return {true, RequiredImm};
11734 }
11735 // 4'b1100
11736 if ((V & 0x7FC0FFFFFFFFFFFFULL) == 0x4000000000000000ULL ||
11737 (V & 0x7FC0FFFFFFFFFFFFULL) == 0x3FC0000000000000ULL) {
11738 RequiredImm =
11739 (0b11100 << 8) | (((V >> 56) & 0xC0) ^ 0x40) | ((V >> 48) & 0x3F);
11740 return {true, RequiredImm};
11741 }
11742 // 4'b1001
11743 auto sameBitsPreByte = [](uint64_t x) -> std::pair<bool, uint8_t> {
11744 uint8_t res = 0;
11745 for (int i = 0; i < 8; ++i) {
11746 uint8_t byte = x & 0xFF;
11747 if (byte == 0 || byte == 0xFF)
11748 res |= ((byte & 1) << i);
11749 else
11750 return {false, 0};
11751 x >>= 8;
11752 }
11753 return {true, res};
11754 };
11755 auto [IsSame, Suffix] = sameBitsPreByte(V);
11756 if (IsSame) {
11757 RequiredImm = (0b11001 << 8) | Suffix;
11758 return {true, RequiredImm};
11759 }
11760 }
11761 return {false, RequiredImm};
11762}
11763
11765 EVT VT) const {
11766 if (!Subtarget.hasExtLSX())
11767 return false;
11768
11769 if (VT == MVT::f32) {
11770 uint64_t masked = Imm.bitcastToAPInt().getZExtValue() & 0x7e07ffff;
11771 return (masked == 0x3e000000 || masked == 0x40000000);
11772 }
11773
11774 if (VT == MVT::f64) {
11775 uint64_t masked = Imm.bitcastToAPInt().getZExtValue() & 0x7fc0ffffffffffff;
11776 return (masked == 0x3fc0000000000000 || masked == 0x4000000000000000);
11777 }
11778
11779 return false;
11780}
11781
11782// Only form FP_TO_SINT_SAT from clamp/NaN-guard idioms when it will be lowered
11783// to a single [X]VFTINTRZ/FTINTRZ, otherwise the generic expansion is worse
11784// than the original sequence.
11785bool LoongArchTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11786 EVT VT) const {
11787 if (!isOperationLegalOrCustom(Op, VT))
11788 return false;
11789 if (VT.isVector())
11790 return FPVT.getScalarSizeInBits() == VT.getScalarSizeInBits();
11791 if (FPVT == MVT::f32)
11792 return VT.getSizeInBits() == 32 || Subtarget.hasBasicD();
11793 return FPVT == MVT::f64 && Subtarget.hasBasicD();
11794}
11795
11797LoongArchTargetLowering::getFPImmAction(const APFloat &Imm, EVT VT,
11798 bool ForCodeSize) const {
11799 // TODO: Maybe need more checks here after vector extension is supported.
11800 if (VT == MVT::f32 && !Subtarget.hasBasicF())
11802 if (VT == MVT::f64 && !Subtarget.hasBasicD())
11804 if (Imm.isZero() || isFPImmVLDILegal(Imm, VT))
11805 return FPImmAction::Legal;
11806
11807 // Immediates the size of a GPR are built from their bits. Others are built in
11808 // lowerConstantFP.
11809 if (VT.getSizeInBits() == Subtarget.getGRLen() && isFPImmCheapInGPR(Imm, VT))
11810 return FPImmAction::Bitcast;
11812}
11813
11815 EVT VT) const {
11816 // Count the instructions to generate the bits and move them to a float
11817 // register.
11818 auto Seq =
11819 LoongArchMatInt::generateInstSeq(Imm.bitcastToAPInt().getSExtValue());
11820 int InsNum = Seq.size() + ((VT == MVT::f64 && !Subtarget.is64Bit()) ? 2 : 1);
11821 return InsNum <= MaterializeFPImmInsNum || Imm.isOne();
11822}
11823
11825 return true;
11826}
11827
11829 return true;
11830}
11831
11832bool LoongArchTargetLowering::shouldInsertFencesForAtomic(
11833 const Instruction *I) const {
11834 if (!Subtarget.is64Bit())
11835 return isa<LoadInst>(I) || isa<StoreInst>(I);
11836
11837 if (isa<LoadInst>(I))
11838 return true;
11839
11840 // On LA64, atomic store operations with IntegerBitWidth of 32 and 64 do not
11841 // require fences beacuse we can use amswap_db.[w/d].
11842 Type *Ty = I->getOperand(0)->getType();
11843 if (isa<StoreInst>(I) && Ty->isIntegerTy()) {
11844 unsigned Size = Ty->getIntegerBitWidth();
11845 return (Size == 8 || Size == 16);
11846 }
11847
11848 return false;
11849}
11850
11852 LLVMContext &Context,
11853 EVT VT) const {
11854 if (!VT.isVector())
11855 return getPointerTy(DL);
11857}
11858
11860 unsigned AddressSpace, EVT MemVT, const MachineFunction &MF) const {
11861 // Do not merge to float value size (128 or 256 bits) if no implicit
11862 // float attribute is set.
11863 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
11864 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
11865 if (NoFloat)
11866 return MemVT.getSizeInBits() <= MaxIntSize;
11867
11868 // Make sure we don't merge greater than our maximum supported vector width.
11869 if (Subtarget.hasExtLASX())
11870 MaxIntSize = 256;
11871 else if (Subtarget.hasExtLSX())
11872 MaxIntSize = 128;
11873
11874 return MemVT.getSizeInBits() <= MaxIntSize;
11875}
11876
11878 EVT VT = Y.getValueType();
11879
11880 if (VT.isVector())
11881 return Subtarget.hasExtLSX() && VT.isInteger();
11882
11883 return VT.isScalarInteger() && !isa<ConstantSDNode>(Y);
11884}
11885
11888 MachineFunction &MF, unsigned Intrinsic) const {
11889 switch (Intrinsic) {
11890 default:
11891 return;
11892 case Intrinsic::loongarch_masked_atomicrmw_xchg_i32:
11893 case Intrinsic::loongarch_masked_atomicrmw_add_i32:
11894 case Intrinsic::loongarch_masked_atomicrmw_sub_i32:
11895 case Intrinsic::loongarch_masked_atomicrmw_nand_i32: {
11896 IntrinsicInfo Info;
11898 Info.memVT = MVT::i32;
11899 Info.ptrVal = I.getArgOperand(0);
11900 Info.offset = 0;
11901 Info.align = Align(4);
11904 Infos.push_back(Info);
11905 return;
11906 // TODO: Add more Intrinsics later.
11907 }
11908 }
11909}
11910
11911// When -mlamcas is enabled, MinCmpXchgSizeInBits will be set to 8,
11912// atomicrmw and/or/xor operations with operands less than 32 bits cannot be
11913// expanded to am{and/or/xor}[_db].w through AtomicExpandPass. To prevent
11914// regression, we need to implement it manually.
11917
11919 Op == AtomicRMWInst::And) &&
11920 "Unable to expand");
11921 unsigned MinWordSize = 4;
11922
11923 IRBuilder<> Builder(AI);
11924 LLVMContext &Ctx = Builder.getContext();
11925 const DataLayout &DL = AI->getDataLayout();
11926 Type *ValueType = AI->getType();
11927 Type *WordType = Type::getIntNTy(Ctx, MinWordSize * 8);
11928
11929 Value *Addr = AI->getPointerOperand();
11930 PointerType *PtrTy = cast<PointerType>(Addr->getType());
11931 IntegerType *IntTy = DL.getIndexType(Ctx, PtrTy->getAddressSpace());
11932
11933 Value *AlignedAddr = Builder.CreateIntrinsic(
11934 Intrinsic::ptrmask, {PtrTy, IntTy},
11935 {Addr, ConstantInt::get(IntTy, ~(uint64_t)(MinWordSize - 1))}, nullptr,
11936 "AlignedAddr");
11937
11938 Value *AddrInt = Builder.CreatePtrToInt(Addr, IntTy);
11939 Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
11940 Value *ShiftAmt = Builder.CreateShl(PtrLSB, 3);
11941 ShiftAmt = Builder.CreateTrunc(ShiftAmt, WordType, "ShiftAmt");
11942 Value *Mask = Builder.CreateShl(
11943 ConstantInt::get(WordType,
11944 (1 << (DL.getTypeStoreSize(ValueType) * 8)) - 1),
11945 ShiftAmt, "Mask");
11946 Value *Inv_Mask = Builder.CreateNot(Mask, "Inv_Mask");
11947 Value *ValOperand_Shifted =
11948 Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), WordType),
11949 ShiftAmt, "ValOperand_Shifted");
11950 Value *NewOperand;
11951 if (Op == AtomicRMWInst::And)
11952 NewOperand = Builder.CreateOr(ValOperand_Shifted, Inv_Mask, "AndOperand");
11953 else
11954 NewOperand = ValOperand_Shifted;
11955
11956 AtomicRMWInst *NewAI =
11957 Builder.CreateAtomicRMW(Op, AlignedAddr, NewOperand, Align(MinWordSize),
11958 AI->getOrdering(), AI->getSyncScopeID());
11959
11960 Value *Shift = Builder.CreateLShr(NewAI, ShiftAmt, "shifted");
11961 Value *Trunc = Builder.CreateTrunc(Shift, ValueType, "extracted");
11962 Value *FinalOldResult = Builder.CreateBitCast(Trunc, ValueType);
11963 AI->replaceAllUsesWith(FinalOldResult);
11964 AI->eraseFromParent();
11965}
11966
11969 const AtomicRMWInst *AI) const {
11970 // TODO: Add more AtomicRMWInst that needs to be extended.
11971
11972 // Since floating-point operation requires a non-trivial set of data
11973 // operations, use CmpXChg to expand.
11974 if (AI->isFloatingPointOperation() ||
11980
11981 if (Subtarget.hasLAM_BH() && Subtarget.is64Bit() &&
11984 AI->getOperation() == AtomicRMWInst::Sub)) {
11986 }
11987
11988 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11989 if (Subtarget.hasLAMCAS()) {
11990 if (Size < 32 && (AI->getOperation() == AtomicRMWInst::And ||
11994 if (AI->getOperation() == AtomicRMWInst::Nand || Size < 32)
11996 }
11997
11998 if (Size == 8 || Size == 16)
12001}
12002
12003static Intrinsic::ID
12005 AtomicRMWInst::BinOp BinOp) {
12006 if (GRLen == 64) {
12007 switch (BinOp) {
12008 default:
12009 llvm_unreachable("Unexpected AtomicRMW BinOp");
12011 return Intrinsic::loongarch_masked_atomicrmw_xchg_i64;
12012 case AtomicRMWInst::Add:
12013 return Intrinsic::loongarch_masked_atomicrmw_add_i64;
12014 case AtomicRMWInst::Sub:
12015 return Intrinsic::loongarch_masked_atomicrmw_sub_i64;
12017 return Intrinsic::loongarch_masked_atomicrmw_nand_i64;
12019 return Intrinsic::loongarch_masked_atomicrmw_umax_i64;
12021 return Intrinsic::loongarch_masked_atomicrmw_umin_i64;
12022 case AtomicRMWInst::Max:
12023 return Intrinsic::loongarch_masked_atomicrmw_max_i64;
12024 case AtomicRMWInst::Min:
12025 return Intrinsic::loongarch_masked_atomicrmw_min_i64;
12026 // TODO: support other AtomicRMWInst.
12027 }
12028 }
12029
12030 if (GRLen == 32) {
12031 switch (BinOp) {
12032 default:
12033 llvm_unreachable("Unexpected AtomicRMW BinOp");
12035 return Intrinsic::loongarch_masked_atomicrmw_xchg_i32;
12036 case AtomicRMWInst::Add:
12037 return Intrinsic::loongarch_masked_atomicrmw_add_i32;
12038 case AtomicRMWInst::Sub:
12039 return Intrinsic::loongarch_masked_atomicrmw_sub_i32;
12041 return Intrinsic::loongarch_masked_atomicrmw_nand_i32;
12043 return Intrinsic::loongarch_masked_atomicrmw_umax_i32;
12045 return Intrinsic::loongarch_masked_atomicrmw_umin_i32;
12046 case AtomicRMWInst::Max:
12047 return Intrinsic::loongarch_masked_atomicrmw_max_i32;
12048 case AtomicRMWInst::Min:
12049 return Intrinsic::loongarch_masked_atomicrmw_min_i32;
12050 // TODO: support other AtomicRMWInst.
12051 }
12052 }
12053
12054 llvm_unreachable("Unexpected GRLen\n");
12055}
12056
12059 const AtomicCmpXchgInst *CI) const {
12060
12061 if (Subtarget.hasLAMCAS())
12063
12065 if (Size == 8 || Size == 16)
12068}
12069
12071 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
12072 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
12073 unsigned GRLen = Subtarget.getGRLen();
12074 AtomicOrdering FailOrd = CI->getFailureOrdering();
12075 Value *FailureOrdering =
12076 Builder.getIntN(Subtarget.getGRLen(), static_cast<uint64_t>(FailOrd));
12077 Intrinsic::ID CmpXchgIntrID = Intrinsic::loongarch_masked_cmpxchg_i32;
12078 if (GRLen == 64) {
12079 CmpXchgIntrID = Intrinsic::loongarch_masked_cmpxchg_i64;
12080 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
12081 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
12082 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12083 }
12084 Type *Tys[] = {AlignedAddr->getType()};
12085 Value *Result = Builder.CreateIntrinsic(
12086 CmpXchgIntrID, Tys, {AlignedAddr, CmpVal, NewVal, Mask, FailureOrdering});
12087 if (GRLen == 64)
12088 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12089 return Result;
12090}
12091
12093 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
12094 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
12095 // In the case of an atomicrmw xchg with a constant 0/-1 operand, replace
12096 // the atomic instruction with an AtomicRMWInst::And/Or with appropriate
12097 // mask, as this produces better code than the LL/SC loop emitted by
12098 // int_loongarch_masked_atomicrmw_xchg.
12099 if (AI->getOperation() == AtomicRMWInst::Xchg &&
12102 if (CVal->isZero())
12103 return Builder.CreateAtomicRMW(AtomicRMWInst::And, AlignedAddr,
12104 Builder.CreateNot(Mask, "Inv_Mask"),
12105 AI->getAlign(), Ord);
12106 if (CVal->isMinusOne())
12107 return Builder.CreateAtomicRMW(AtomicRMWInst::Or, AlignedAddr, Mask,
12108 AI->getAlign(), Ord);
12109 }
12110
12111 unsigned GRLen = Subtarget.getGRLen();
12112 Value *Ordering =
12113 Builder.getIntN(GRLen, static_cast<uint64_t>(AI->getOrdering()));
12114 Type *Tys[] = {AlignedAddr->getType()};
12116 AI->getModule(),
12118
12119 if (GRLen == 64) {
12120 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
12121 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12122 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
12123 }
12124
12125 Value *Result;
12126
12127 // Must pass the shift amount needed to sign extend the loaded value prior
12128 // to performing a signed comparison for min/max. ShiftAmt is the number of
12129 // bits to shift the value into position. Pass GRLen-ShiftAmt-ValWidth, which
12130 // is the number of bits to left+right shift the value in order to
12131 // sign-extend.
12132 if (AI->getOperation() == AtomicRMWInst::Min ||
12134 const DataLayout &DL = AI->getDataLayout();
12135 unsigned ValWidth =
12136 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
12137 Value *SextShamt =
12138 Builder.CreateSub(Builder.getIntN(GRLen, GRLen - ValWidth), ShiftAmt);
12139 Result = Builder.CreateCall(LlwOpScwLoop,
12140 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
12141 } else {
12142 Result =
12143 Builder.CreateCall(LlwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
12144 }
12145
12146 if (GRLen == 64)
12147 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12148 return Result;
12149}
12150
12152 const MachineFunction &MF, EVT VT) const {
12153 VT = VT.getScalarType();
12154
12155 if (!VT.isSimple())
12156 return false;
12157
12158 switch (VT.getSimpleVT().SimpleTy) {
12159 case MVT::f32:
12160 case MVT::f64:
12161 return true;
12162 default:
12163 break;
12164 }
12165
12166 return false;
12167}
12168
12170 ExceptionHandling EH, const Constant *PersonalityFn) const {
12171 return LoongArch::R4;
12172}
12173
12175 ExceptionHandling EH, const Constant *PersonalityFn) const {
12176 return LoongArch::R5;
12177}
12178
12179//===----------------------------------------------------------------------===//
12180// Target Optimization Hooks
12181//===----------------------------------------------------------------------===//
12182
12185 // Feature FRECIPE instructions relative accuracy is 2^-14.
12186 // IEEE float has 23 digits and double has 52 digits.
12187 int RefinementSteps = VT.getScalarType() == MVT::f64 ? 2 : 1;
12188 return RefinementSteps;
12189}
12190
12191static bool
12193 assert(Subtarget.hasFrecipe() &&
12194 "Reciprocal estimate queried on unsupported target");
12195
12196 if (!VT.isSimple())
12197 return false;
12198
12199 switch (VT.getSimpleVT().SimpleTy) {
12200 case MVT::f32:
12201 // f32 is the base type for reciprocal estimate instructions.
12202 return true;
12203
12204 case MVT::f64:
12205 return Subtarget.hasBasicD();
12206
12207 case MVT::v4f32:
12208 case MVT::v2f64:
12209 return Subtarget.hasExtLSX();
12210
12211 case MVT::v8f32:
12212 case MVT::v4f64:
12213 return Subtarget.hasExtLASX();
12214
12215 default:
12216 return false;
12217 }
12218}
12219
12221 SelectionDAG &DAG, int Enabled,
12222 int &RefinementSteps,
12223 bool &UseOneConstNR,
12224 bool Reciprocal) const {
12226 "Enabled should never be Disabled here");
12227
12228 if (!Subtarget.hasFrecipe())
12229 return SDValue();
12230
12231 SDLoc DL(Operand);
12232 EVT VT = Operand.getValueType();
12233
12234 // Check supported types.
12235 if (!isSupportedReciprocalEstimateType(VT, Subtarget))
12236 return SDValue();
12237
12238 // Handle refinement steps.
12239 if (RefinementSteps == ReciprocalEstimate::Unspecified)
12240 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12241
12242 // LoongArch only has FRSQRTE which is 1.0 / sqrt(x).
12243 UseOneConstNR = false;
12244 SDValue Rsqrt = DAG.getNode(LoongArchISD::FRSQRTE, DL, VT, Operand);
12245
12246 // If the caller wants 1.0 / sqrt(x), or if further refinement steps
12247 // are needed (which rely on the reciprocal form), return the raw reciprocal
12248 // estimate.
12249 if (Reciprocal || RefinementSteps > 0)
12250 return Rsqrt;
12251
12252 // Otherwise, return sqrt(x) by multiplying with the operand.
12253 return DAG.getNode(ISD::FMUL, DL, VT, Operand, Rsqrt);
12254}
12255
12257 SelectionDAG &DAG,
12258 int Enabled,
12259 int &RefinementSteps) const {
12261 "Enabled should never be Disabled here");
12262
12263 if (!Subtarget.hasFrecipe())
12264 return SDValue();
12265
12266 SDLoc DL(Operand);
12267 EVT VT = Operand.getValueType();
12268
12269 // Check supported types.
12270 if (!isSupportedReciprocalEstimateType(VT, Subtarget))
12271 return SDValue();
12272
12273 if (RefinementSteps == ReciprocalEstimate::Unspecified)
12274 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12275
12276 // FRECIPE computes 1.0 / x.
12277 return DAG.getNode(LoongArchISD::FRECIPE, DL, VT, Operand);
12278}
12279
12280//===----------------------------------------------------------------------===//
12281// LoongArch Inline Assembly Support
12282//===----------------------------------------------------------------------===//
12283
12285LoongArchTargetLowering::getConstraintType(StringRef Constraint) const {
12286 // LoongArch specific constraints in GCC: config/loongarch/constraints.md
12287 //
12288 // 'f': A floating-point register (if available).
12289 // 'k': A memory operand whose address is formed by a base register and
12290 // (optionally scaled) index register.
12291 // 'l': A signed 16-bit constant.
12292 // 'm': A memory operand whose address is formed by a base register and
12293 // offset that is suitable for use in instructions with the same
12294 // addressing mode as st.w and ld.w.
12295 // 'q': A general-purpose register except for $r0 and $r1 (for the csrxchg
12296 // instruction)
12297 // 'I': A signed 12-bit constant (for arithmetic instructions).
12298 // 'J': Integer zero.
12299 // 'K': An unsigned 12-bit constant (for logic instructions).
12300 // "ZB": An address that is held in a general-purpose register. The offset is
12301 // zero.
12302 // "ZC": A memory operand whose address is formed by a base register and
12303 // offset that is suitable for use in instructions with the same
12304 // addressing mode as ll.w and sc.w.
12305 if (Constraint.size() == 1) {
12306 switch (Constraint[0]) {
12307 default:
12308 break;
12309 case 'f':
12310 case 'q':
12311 return C_RegisterClass;
12312 case 'l':
12313 case 'I':
12314 case 'J':
12315 case 'K':
12316 return C_Immediate;
12317 case 'k':
12318 return C_Memory;
12319 }
12320 }
12321
12322 if (Constraint == "ZC" || Constraint == "ZB")
12323 return C_Memory;
12324
12325 // 'm' is handled here.
12326 return TargetLowering::getConstraintType(Constraint);
12327}
12328
12329InlineAsm::ConstraintCode LoongArchTargetLowering::getInlineAsmMemConstraint(
12330 StringRef ConstraintCode) const {
12331 return StringSwitch<InlineAsm::ConstraintCode>(ConstraintCode)
12335 .Default(TargetLowering::getInlineAsmMemConstraint(ConstraintCode));
12336}
12337
12338std::pair<unsigned, const TargetRegisterClass *>
12339LoongArchTargetLowering::getRegForInlineAsmConstraint(
12340 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12341 // First, see if this is a constraint that directly corresponds to a LoongArch
12342 // register class.
12343 if (Constraint.size() == 1) {
12344 switch (Constraint[0]) {
12345 case 'r':
12346 // TODO: Support fixed vectors up to GRLen?
12347 if (VT.isVector())
12348 break;
12349 return std::make_pair(0U, &LoongArch::GPRRegClass);
12350 case 'q':
12351 return std::make_pair(0U, &LoongArch::GPRNoR0R1RegClass);
12352 case 'f':
12353 if (Subtarget.hasBasicF() && VT == MVT::f32)
12354 return std::make_pair(0U, &LoongArch::FPR32RegClass);
12355 if (Subtarget.hasBasicD() && VT == MVT::f64)
12356 return std::make_pair(0U, &LoongArch::FPR64RegClass);
12357 if (Subtarget.hasExtLSX() &&
12358 TRI->isTypeLegalForClass(LoongArch::LSX128RegClass, VT))
12359 return std::make_pair(0U, &LoongArch::LSX128RegClass);
12360 if (Subtarget.hasExtLSX() && VT == MVT::i128)
12361 return std::make_pair(0U, &LoongArch::LSX128RegClass);
12362 if (Subtarget.hasExtLASX() &&
12363 TRI->isTypeLegalForClass(LoongArch::LASX256RegClass, VT))
12364 return std::make_pair(0U, &LoongArch::LASX256RegClass);
12365 break;
12366 default:
12367 break;
12368 }
12369 }
12370
12371 // TargetLowering::getRegForInlineAsmConstraint uses the name of the TableGen
12372 // record (e.g. the "R0" in `def R0`) to choose registers for InlineAsm
12373 // constraints while the official register name is prefixed with a '$'. So we
12374 // clip the '$' from the original constraint string (e.g. {$r0} to {r0}.)
12375 // before it being parsed. And TargetLowering::getRegForInlineAsmConstraint is
12376 // case insensitive, so no need to convert the constraint to upper case here.
12377 //
12378 // For now, no need to support ABI names (e.g. `$a0`) as clang will correctly
12379 // decode the usage of register name aliases into their official names. And
12380 // AFAIK, the not yet upstreamed `rustc` for LoongArch will always use
12381 // official register names.
12382 if (Constraint.starts_with("{$r") || Constraint.starts_with("{$f") ||
12383 Constraint.starts_with("{$vr") || Constraint.starts_with("{$xr")) {
12384 bool IsFP = Constraint[2] == 'f';
12385 std::pair<StringRef, StringRef> Temp = Constraint.split('$');
12386 std::pair<unsigned, const TargetRegisterClass *> R;
12388 TRI, join_items("", Temp.first, Temp.second), VT);
12389 // Match those names to the widest floating point register type available.
12390 if (IsFP) {
12391 unsigned RegNo = R.first;
12392 if (LoongArch::F0 <= RegNo && RegNo <= LoongArch::F31) {
12393 if (Subtarget.hasBasicD() && (VT == MVT::f64 || VT == MVT::Other)) {
12394 unsigned DReg = RegNo - LoongArch::F0 + LoongArch::F0_64;
12395 return std::make_pair(DReg, &LoongArch::FPR64RegClass);
12396 }
12397 }
12398 }
12399 return R;
12400 }
12401
12402 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12403}
12404
12405void LoongArchTargetLowering::LowerAsmOperandForConstraint(
12406 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
12407 SelectionDAG &DAG) const {
12408 // Currently only support length 1 constraints.
12409 if (Constraint.size() == 1) {
12410 switch (Constraint[0]) {
12411 case 'l':
12412 // Validate & create a 16-bit signed immediate operand.
12413 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12414 uint64_t CVal = C->getSExtValue();
12415 if (isInt<16>(CVal))
12416 Ops.push_back(DAG.getSignedTargetConstant(CVal, SDLoc(Op),
12417 Subtarget.getGRLenVT()));
12418 }
12419 return;
12420 case 'I':
12421 // Validate & create a 12-bit signed immediate operand.
12422 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12423 uint64_t CVal = C->getSExtValue();
12424 if (isInt<12>(CVal))
12425 Ops.push_back(DAG.getSignedTargetConstant(CVal, SDLoc(Op),
12426 Subtarget.getGRLenVT()));
12427 }
12428 return;
12429 case 'J':
12430 // Validate & create an integer zero operand.
12431 if (auto *C = dyn_cast<ConstantSDNode>(Op))
12432 if (C->getZExtValue() == 0)
12433 Ops.push_back(
12434 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getGRLenVT()));
12435 return;
12436 case 'K':
12437 // Validate & create a 12-bit unsigned immediate operand.
12438 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12439 uint64_t CVal = C->getZExtValue();
12440 if (isUInt<12>(CVal))
12441 Ops.push_back(
12442 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getGRLenVT()));
12443 }
12444 return;
12445 default:
12446 break;
12447 }
12448 }
12450}
12451
12452#define GET_REGISTER_MATCHER
12453#include "LoongArchGenAsmMatcher.inc"
12454
12457 const MachineFunction &MF) const {
12458 std::pair<StringRef, StringRef> Name = StringRef(RegName).split('$');
12459 std::string NewRegName = Name.second.str();
12460 Register Reg = MatchRegisterAltName(NewRegName);
12461 if (!Reg)
12462 Reg = MatchRegisterName(NewRegName);
12463 if (!Reg)
12464 return Reg;
12465 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12466 if (!ReservedRegs.test(Reg))
12467 report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12468 StringRef(RegName) + "\"."));
12469 return Reg;
12470}
12471
12473 EVT VT, SDValue C) const {
12474 // TODO: Support vectors.
12475 if (!VT.isScalarInteger())
12476 return false;
12477
12478 // Omit the optimization if the data size exceeds GRLen.
12479 if (VT.getSizeInBits() > Subtarget.getGRLen())
12480 return false;
12481
12482 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12483 const APInt &Imm = ConstNode->getAPIntValue();
12484 // Break MUL into (SLLI + ADD/SUB) or ALSL.
12485 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12486 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12487 return true;
12488 // Break MUL into (ALSL x, (SLLI x, imm0), imm1).
12489 if (ConstNode->hasOneUse() &&
12490 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12491 (Imm - 8).isPowerOf2() || (Imm - 16).isPowerOf2()))
12492 return true;
12493 // Break (MUL x, imm) into (ADD (SLLI x, s0), (SLLI x, s1)),
12494 // in which the immediate has two set bits. Or Break (MUL x, imm)
12495 // into (SUB (SLLI x, s0), (SLLI x, s1)), in which the immediate
12496 // equals to (1 << s0) - (1 << s1).
12497 if (ConstNode->hasOneUse() && !(Imm.sge(-2048) && Imm.sle(4095))) {
12498 unsigned Shifts = Imm.countr_zero();
12499 // Reject immediates which can be composed via a single LUI.
12500 if (Shifts >= 12)
12501 return false;
12502 // Reject multiplications can be optimized to
12503 // (SLLI (ALSL x, x, 1/2/3/4), s).
12504 APInt ImmPop = Imm.ashr(Shifts);
12505 if (ImmPop == 3 || ImmPop == 5 || ImmPop == 9 || ImmPop == 17)
12506 return false;
12507 // We do not consider the case `(-Imm - ImmSmall).isPowerOf2()`,
12508 // since it needs one more instruction than other 3 cases.
12509 APInt ImmSmall = APInt(Imm.getBitWidth(), 1ULL << Shifts, true);
12510 if ((Imm - ImmSmall).isPowerOf2() || (Imm + ImmSmall).isPowerOf2() ||
12511 (ImmSmall - Imm).isPowerOf2())
12512 return true;
12513 }
12514 }
12515
12516 return false;
12517}
12518
12520 const AddrMode &AM,
12521 Type *Ty, unsigned AS,
12522 Instruction *I) const {
12523 // LoongArch has four basic addressing modes:
12524 // 1. reg
12525 // 2. reg + 12-bit signed offset
12526 // 3. reg + 14-bit signed offset left-shifted by 2
12527 // 4. reg1 + reg2
12528 // TODO: Add more checks after support vector extension.
12529
12530 // No global is ever allowed as a base.
12531 if (AM.BaseGV)
12532 return false;
12533
12534 // Require a 12-bit signed offset or 14-bit signed offset left-shifted by 2
12535 // with `UAL` feature.
12536 if (!isInt<12>(AM.BaseOffs) &&
12537 !(isShiftedInt<14, 2>(AM.BaseOffs) && Subtarget.hasUAL()))
12538 return false;
12539
12540 switch (AM.Scale) {
12541 case 0:
12542 // "r+i" or just "i", depending on HasBaseReg.
12543 break;
12544 case 1:
12545 // "r+r+i" is not allowed.
12546 if (AM.HasBaseReg && AM.BaseOffs)
12547 return false;
12548 // Otherwise we have "r+r" or "r+i".
12549 break;
12550 case 2:
12551 // "2*r+r" or "2*r+i" is not allowed.
12552 if (AM.HasBaseReg || AM.BaseOffs)
12553 return false;
12554 // Allow "2*r" as "r+r".
12555 break;
12556 default:
12557 return false;
12558 }
12559
12560 return true;
12561}
12562
12564 return isInt<12>(Imm);
12565}
12566
12568 return isInt<12>(Imm);
12569}
12570
12572 // Zexts are free if they can be combined with a load.
12573 // Don't advertise i32->i64 zextload as being free for LA64. It interacts
12574 // poorly with type legalization of compares preferring sext.
12575 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
12576 EVT MemVT = LD->getMemoryVT();
12577 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
12578 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12579 LD->getExtensionType() == ISD::ZEXTLOAD))
12580 return true;
12581 }
12582
12583 return TargetLowering::isZExtFree(Val, VT2);
12584}
12585
12587 EVT DstVT) const {
12588 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
12589}
12590
12592 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
12593}
12594
12596 // TODO: Support vectors.
12597 if (Y.getValueType().isVector())
12598 return false;
12599
12600 return true;
12601}
12602
12604 // LAMCAS will use amcas[_DB].{b/h/w/d} which does not require extension.
12605 return Subtarget.hasLAMCAS() ? ISD::ANY_EXTEND : ISD::SIGN_EXTEND;
12606}
12607
12609 Type *Ty, bool IsSigned) const {
12610 if (Subtarget.is64Bit() && Ty->isIntegerTy(32))
12611 return true;
12612
12613 return IsSigned;
12614}
12615
12617 // Return false to suppress the unnecessary extensions if the LibCall
12618 // arguments or return value is a float narrower than GRLEN on a soft FP ABI.
12619 if (Subtarget.isSoftFPABI() && (Type.isFloatingPoint() && !Type.isVector() &&
12620 Type.getSizeInBits() < Subtarget.getGRLen()))
12621 return false;
12622 return true;
12623}
12624
12625// memcpy, and other memory intrinsics, typically tries to use wider load/store
12626// if the source/dest is aligned and the copy size is large enough. We therefore
12627// want to align such objects passed to memory intrinsics.
12629 unsigned &MinSize,
12630 Align &PrefAlign) const {
12631 if (!isa<MemIntrinsic>(CI))
12632 return false;
12633
12634 if (Subtarget.is64Bit()) {
12635 MinSize = 8;
12636 PrefAlign = Align(8);
12637 } else {
12638 MinSize = 4;
12639 PrefAlign = Align(4);
12640 }
12641
12642 return true;
12643}
12644
12647 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
12648 VT.getVectorElementType() != MVT::i1)
12649 return TypeWidenVector;
12650
12652}
12653
12654bool LoongArchTargetLowering::splitValueIntoRegisterParts(
12655 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12656 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
12657 bool IsABIRegCopy = CC.has_value();
12658 EVT ValueVT = Val.getValueType();
12659
12660 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
12661 PartVT == MVT::f32) {
12662 // Cast the [b]f16 to i16, extend to i32, pad with ones to make a float
12663 // nan, and cast to f32.
12664 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12665 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12666 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12667 DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12668 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12669 Parts[0] = Val;
12670 return true;
12671 }
12672
12673 return false;
12674}
12675
12676SDValue LoongArchTargetLowering::joinRegisterPartsIntoValue(
12677 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12678 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
12679 bool IsABIRegCopy = CC.has_value();
12680
12681 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
12682 PartVT == MVT::f32) {
12683 SDValue Val = Parts[0];
12684
12685 // Cast the f32 to i32, truncate to i16, and cast back to [b]f16.
12686 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12687 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12688 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
12689 return Val;
12690 }
12691
12692 return SDValue();
12693}
12694
12695MVT LoongArchTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
12697 EVT VT) const {
12698 // Use f32 to pass f16.
12699 if (VT == MVT::f16 && Subtarget.hasBasicF())
12700 return MVT::f32;
12701
12703}
12704
12705unsigned LoongArchTargetLowering::getNumRegistersForCallingConv(
12707 // Use f32 to pass f16.
12708 if (VT == MVT::f16 && Subtarget.hasBasicF())
12709 return 1;
12710
12712}
12713
12715 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
12716 const SelectionDAG &DAG, unsigned Depth) const {
12717 unsigned Opc = Op.getOpcode();
12718 Known.resetAll();
12719 switch (Opc) {
12720 default:
12721 break;
12722 case LoongArchISD::VANYNONZERO:
12723 case LoongArchISD::VALLZERO:
12724 case LoongArchISD::VALL_ZERO:
12725 case LoongArchISD::VANY_ZERO:
12726 case LoongArchISD::VALL_NONZERO:
12727 case LoongArchISD::VANY_NONZERO: {
12728 // MOVCF2GR zero-extend the i1 cond to GPR.
12729 Known.Zero.setBitsFrom(1);
12730 break;
12731 }
12732 case LoongArchISD::VPICK_ZEXT_ELT: {
12733 assert(isa<VTSDNode>(Op->getOperand(2)) && "Unexpected operand!");
12734 EVT VT = cast<VTSDNode>(Op->getOperand(2))->getVT();
12735 unsigned VTBits = VT.getScalarSizeInBits();
12736 assert(Known.getBitWidth() >= VTBits && "Unexpected width!");
12737 Known.Zero.setBitsFrom(VTBits);
12738 break;
12739 }
12740 case LoongArchISD::BSTRINS: {
12741 // BSTRINS X, Y, msb, lsb: replace X[msb:lsb] with Y[msb-lsb:0].
12742 unsigned Msb = Op.getConstantOperandVal(2);
12743 unsigned Lsb = Op.getConstantOperandVal(3);
12744 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
12745 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
12746 Known.insertBits(Known2.trunc(Msb - Lsb + 1), Lsb);
12747 break;
12748 }
12749 case LoongArchISD::BSTRPICK: {
12750 // BSTRPICK X, msb, lsb: zero-extend X[msb:lsb].
12751 unsigned BitWidth = Known.getBitWidth();
12752 unsigned Msb = Op.getConstantOperandVal(1);
12753 unsigned Lsb = Op.getConstantOperandVal(2);
12754 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
12755 Known = Known.extractBits(Msb - Lsb + 1, Lsb).zext(BitWidth);
12756 break;
12757 }
12758 }
12759}
12760
12762 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
12763 unsigned Depth) const {
12764 switch (Op.getOpcode()) {
12765 default:
12766 break;
12767 case LoongArchISD::BSTRINS: {
12768 unsigned BitWidth = Op.getScalarValueSizeInBits();
12769 unsigned Msb = Op.getConstantOperandVal(2);
12770 unsigned Lsb = Op.getConstantOperandVal(3);
12771 // The bits above msb come from X.
12772 if (Msb != BitWidth - 1) {
12773 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
12774 return std::min(Tmp, BitWidth - 1 - Msb);
12775 }
12776 // The high bits come from Y shifted left by lsb.
12777 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(1), Depth + 1);
12778 return Tmp > Lsb ? Tmp - Lsb : 1;
12779 }
12780 }
12781 return 1;
12782}
12783
12785 SDValue Op, const APInt &OriginalDemandedBits,
12786 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
12787 unsigned Depth) const {
12788 EVT VT = Op.getValueType();
12789 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
12790 unsigned Opc = Op.getOpcode();
12791 switch (Opc) {
12792 default:
12793 break;
12794 case LoongArchISD::CRC_W_B_W:
12795 case LoongArchISD::CRC_W_H_W:
12796 case LoongArchISD::CRCC_W_B_W:
12797 case LoongArchISD::CRCC_W_H_W: {
12798 KnownBits KnownSrc;
12799 APInt DemandedSrcBits =
12800 APInt::getLowBitsSet(BitWidth, (Opc == LoongArchISD::CRC_W_B_W ||
12801 Opc == LoongArchISD::CRCC_W_B_W)
12802 ? 8
12803 : 16);
12804 return SimplifyDemandedBits(Op.getOperand(1), DemandedSrcBits,
12805 OriginalDemandedElts, KnownSrc, TLO, Depth + 1);
12806 }
12807 case LoongArchISD::VMSKLTZ:
12808 case LoongArchISD::XVMSKLTZ: {
12809 SDValue Src = Op.getOperand(0);
12810 MVT SrcVT = Src.getSimpleValueType();
12811 unsigned SrcBits = SrcVT.getScalarSizeInBits();
12812 unsigned NumElts = SrcVT.getVectorNumElements();
12813
12814 // If we don't need the sign bits at all just return zero.
12815 if (OriginalDemandedBits.countr_zero() >= NumElts)
12816 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
12817
12818 // Only demand the vector elements of the sign bits we need.
12819 APInt KnownUndef, KnownZero;
12820 APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
12821 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
12822 TLO, Depth + 1))
12823 return true;
12824
12825 Known.Zero = KnownZero.zext(BitWidth);
12826 Known.Zero.setHighBits(BitWidth - NumElts);
12827
12828 // [X]VMSKLTZ only uses the MSB from each vector element.
12829 KnownBits KnownSrc;
12830 APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
12831 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
12832 Depth + 1))
12833 return true;
12834
12835 if (KnownSrc.One[SrcBits - 1])
12836 Known.One.setLowBits(NumElts);
12837 else if (KnownSrc.Zero[SrcBits - 1])
12838 Known.Zero.setLowBits(NumElts);
12839
12840 // Attempt to avoid multi-use ops if we don't need anything from it.
12842 Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
12843 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
12844 return false;
12845 }
12846 }
12847
12849 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
12850}
12851
12853 unsigned Opc = VecOp.getOpcode();
12854
12855 // Assume target opcodes can't be scalarized.
12856 // TODO - do we have any exceptions?
12857 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
12858 return false;
12859
12860 // If the vector op is not supported, try to convert to scalar.
12861 EVT VecVT = VecOp.getValueType();
12863 return true;
12864
12865 // If the vector op is supported, but the scalar op is not, the transform may
12866 // not be worthwhile.
12867 EVT ScalarVT = VecVT.getScalarType();
12868 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
12869}
12870
12873 unsigned Index) const {
12876
12877 // Extract a 128-bit subvector from index 0 of a 256-bit vector is free.
12878 if (Index == 0)
12881}
12882
12884 unsigned Index) const {
12885 EVT EltVT = VT.getScalarType();
12886
12887 // Extract a scalar FP value from index 0 of a vector is free.
12888 return (EltVT == MVT::f32 || EltVT == MVT::f64) && Index == 0;
12889}
12890
12892 const MachineFunction &MF) const {
12893
12894 // If the function specifically requests inline stack probes, emit them.
12895 if (MF.getFunction().hasFnAttribute("probe-stack"))
12896 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
12897 "inline-asm";
12898
12899 return false;
12900}
12901
12903 Align StackAlign) const {
12904 // The default stack probe size is 4096 if the function has no
12905 // stack-probe-size attribute.
12906 const Function &Fn = MF.getFunction();
12907 unsigned StackProbeSize =
12908 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
12909 // Round down to the stack alignment.
12910 StackProbeSize = alignDown(StackProbeSize, StackAlign.value());
12911 return StackProbeSize ? StackProbeSize : StackAlign.value();
12912}
12913
12914SDValue
12915LoongArchTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
12916 SelectionDAG &DAG) const {
12918 if (!hasInlineStackProbe(MF))
12919 return SDValue();
12920
12921 const MVT GRLenVT = Subtarget.getGRLenVT();
12922 // Get the inputs.
12923 SDValue Chain = Op.getOperand(0);
12924 SDValue Size = Op.getOperand(1);
12925
12926 const MaybeAlign Align =
12927 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
12928 const SDLoc dl(Op);
12929 const EVT VT = Op.getValueType();
12930
12931 // Construct the new SP value in a GPR.
12932 SDValue SP = DAG.getCopyFromReg(Chain, dl, LoongArch::R3, GRLenVT);
12933 Chain = SP.getValue(1);
12934 SP = DAG.getNode(ISD::SUB, dl, GRLenVT, SP, Size);
12935 if (Align)
12936 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
12937 DAG.getSignedConstant(-Align->value(), dl, VT));
12938
12939 // Set the real SP to the new value with a probing loop.
12940 Chain = DAG.getNode(LoongArchISD::PROBED_ALLOCA, dl, MVT::Other, Chain, SP);
12941 return DAG.getMergeValues({SP, Chain}, dl);
12942}
12943
12946 MachineBasicBlock *MBB) const {
12947 MachineFunction &MF = *MBB->getParent();
12948 MachineBasicBlock::iterator MBBI = MI.getIterator();
12949 DebugLoc DL = MBB->findDebugLoc(MBBI);
12950 const Register TargetReg = MI.getOperand(0).getReg();
12951
12952 const LoongArchInstrInfo *TII = Subtarget.getInstrInfo();
12953 const bool IsLA64 = Subtarget.is64Bit();
12954 const Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
12955 const LoongArchTargetLowering *TLI = Subtarget.getTargetLowering();
12956 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
12957
12958 MachineFunction::iterator MBBInsertPoint = std::next(MBB->getIterator());
12959 MachineBasicBlock *const LoopTestMBB =
12960 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
12961 MF.insert(MBBInsertPoint, LoopTestMBB);
12962 MachineBasicBlock *const ExitMBB =
12963 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
12964 MF.insert(MBBInsertPoint, ExitMBB);
12965 const Register SPReg = LoongArch::R3;
12966 const Register ScratchReg =
12967 MF.getRegInfo().createVirtualRegister(&LoongArch::GPRRegClass);
12968
12969 // ScratchReg = ProbeSize
12970 TII->movImm(*MBB, MBBI, DL, ScratchReg, ProbeSize, MachineInstr::NoFlags);
12971
12972 // LoopTest:
12973 // sub.{w/d} $sp, $sp, ScratchReg
12974 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
12975 TII->get(IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W), SPReg)
12976 .addReg(SPReg)
12977 .addReg(ScratchReg);
12978
12979 // st.{w/d} $zero, $sp, 0
12980 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
12981 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
12982 .addReg(LoongArch::R0)
12983 .addReg(SPReg)
12984 .addImm(0);
12985
12986 // bltu TargetReg, $sp, LoopTest
12987 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(LoongArch::BLTU))
12988 .addReg(TargetReg)
12989 .addReg(SPReg)
12990 .addMBB(LoopTestMBB);
12991
12992 // move $sp, TargetReg
12993 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(LoongArch::OR), SPReg)
12994 .addReg(TargetReg)
12995 .addReg(LoongArch::R0);
12996
12997 ExitMBB->splice(ExitMBB->end(), MBB, std::next(MBBI), MBB->end());
12999
13000 LoopTestMBB->addSuccessor(ExitMBB);
13001 LoopTestMBB->addSuccessor(LoopTestMBB);
13002 MBB->addSuccessor(LoopTestMBB);
13003
13004 MI.eraseFromParent();
13005 MF.getInfo<LoongArchMachineFunctionInfo>()->setDynamicAllocation();
13006 return ExitMBB->begin()->getParent();
13007}
static MCRegister MatchRegisterName(StringRef Name)
static SDValue performSHLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
If the operand is a bitwise AND with a constant RHS, and the shift has a constant RHS and is the only...
static bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType)
static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
unsigned NumParts
return SDValue()
static SDValue performANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue performSELECT_CCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
static SDValue performSETCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
Function Alias Analysis Results
static uint64_t getConstant(const Value *IndexValue)
static SDValue getTargetNode(ConstantPoolSDNode *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned Flags)
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static MachineBasicBlock * emitSelectPseudo(MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode)
static SDValue unpackFromRegLoc(const CSKYSubtarget &Subtarget, SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static bool isSigned(unsigned Opcode)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static SDValue performINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
const MCPhysReg ArgFPR32s[]
static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Dispatching routine to lower various 128-bit LoongArch vector shuffles.
static SDValue lowerVECTOR_SHUFFLE_XVSHUF4I(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVSHUF4I (if possible).
const MCPhysReg ArgVRs[]
static SDValue lowerVECTOR_SHUFFLE_VPICKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPICKEV (if possible).
static SDValue combineSelectToBinOp(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVPICKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPICKOD (if possible).
static SDValue unpackF64OnLA32DSoftABI(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const CCValAssign &HiVA, const SDLoc &DL)
static bool fitsRegularPattern(typename SmallVectorImpl< ValType >::const_iterator Begin, unsigned CheckStride, typename SmallVectorImpl< ValType >::const_iterator End, ValType ExpectedIndex, unsigned ExpectedIndexStride)
Determine whether a range fits a regular pattern of values.
static SDValue lowerVECTOR_SHUFFLE_IsReverse(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE whose result is the reversed source vector.
static SDValue PromoteMaskArithmetic(SDValue N, const SDLoc &DL, EVT VT, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned Depth)
static SDValue performUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performHorizWideningCombine(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static std::pair< SDValue, EVT > stripSignExtendInReg(SDValue V)
static SDValue emitIntrinsicErrorMessage(SDValue Op, StringRef ErrorMsg, SelectionDAG &DAG)
static SDValue ExtendSrcToDst(SDNode *N, SelectionDAG &DAG, unsigned ExtendOp)
static cl::opt< bool > ZeroDivCheck("loongarch-check-zero-division", cl::Hidden, cl::desc("Trap on integer division by zero."), cl::init(false))
static SDValue lowerVECTOR_SHUFFLE_XVPERMI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERMI (if possible).
static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VSHUF(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VSHUF.
static int getEstimateRefinementSteps(EVT VT, const LoongArchSubtarget &Subtarget)
static bool isSupportedReciprocalEstimateType(EVT VT, const LoongArchSubtarget &Subtarget)
static void emitErrorAndReplaceIntrinsicResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, StringRef ErrorMsg, bool WithChain=true)
static SDValue lowerVECTOR_SHUFFLEAsByteRotate(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE as byte rotate (if possible).
static SDValue checkIntrinsicImmArg(SDValue Op, unsigned ImmOp, SelectionDAG &DAG, bool IsSigned=false)
static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVINSVE0(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVINSVE0 (if possible).
static SDValue performMOVFR2GR_SCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VILVH(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VILVH (if possible).
static SDValue performSIGN_EXTEND_INREGCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performDemandedBitsCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI)
static bool CC_LoongArch(const DataLayout &DL, LoongArchABI::ABI ABI, unsigned ValNo, MVT ValVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsRet, Type *OrigTy)
static std::tuple< unsigned, SDValue, EVT > matchBinOpWithSharedOperand(SDValue BinV, SDValue X)
static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
static SDValue performSPLIT_PAIR_F64Combine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performBITCASTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performSRLCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static MachineBasicBlock * emitSplitPairF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorBitSetImm(SDNode *Node, SelectionDAG &DAG)
static SDValue performSETCC_BITCASTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
@ NoMaterializeFPImm
@ MaterializeFPImm2Ins
@ MaterializeFPImm5Ins
@ MaterializeFPImm6Ins
@ MaterializeFPImm3Ins
@ MaterializeFPImm4Ins
static SDValue performEXTENDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVPACKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPACKOD (if possible).
static bool buildVPERMIInfo(ArrayRef< int > Mask, SDValue V1, SDValue V2, SmallVectorImpl< SDValue > &SrcVec, unsigned &MaskImm)
static std::optional< bool > matchSetCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDValue Val)
static SDValue combineAndNotIntoVANDN(SDNode *N, const SDLoc &DL, SelectionDAG &DAG)
Try to fold: (and (xor X, -1), Y) -> (vandn X, Y).
static SDValue lowerBUILD_VECTORAsBroadCastLoad(BuildVectorSDNode *BVOp, const SDLoc &DL, SelectionDAG &DAG)
#define CRC_CASE_EXT_BINARYOP(NAME, NODE)
static SDValue lowerVectorBitRevImm(SDNode *Node, SelectionDAG &DAG)
static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size, unsigned Depth)
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
static SDValue lowerVECTOR_SHUFFLEAsShift(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, const APInt &Zeroable)
Lower VECTOR_SHUFFLE as shift (if possible).
static SDValue lowerVECTOR_SHUFFLE_VSHUF4I(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VSHUF4I (if possible).
static SDValue truncateVecElts(SDNode *Node, SelectionDAG &DAG)
static bool CC_LoongArch_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static MachineBasicBlock * insertDivByZeroTrap(MachineInstr &MI, MachineBasicBlock *MBB)
static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG)
static SDValue lowerVECTOR_SHUFFLE_VEXTRINS(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VEXTRINS (if possible).
static SDValue lowerVectorBitClear(SDNode *Node, SelectionDAG &DAG)
static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VPACKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPACKEV (if possible).
static MachineBasicBlock * emitPseudoVMSKCOND(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue performSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performVANDNCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
Do target-specific dag combines on LoongArchISD::VANDN nodes.
static void replaceVPICKVE2GRResults(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned ResOp)
static SDValue lowerVECTOR_SHUFFLEAsZeroOrAnyExtend(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const APInt &Zeroable)
Lower VECTOR_SHUFFLE as ZERO_EXTEND Or ANY_EXTEND (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVPERMIQ(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERMI_Q (if possible).
static SDValue legalizeIntrinsicImmArg(SDNode *Node, unsigned ImmOp, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, bool IsSigned=false)
static cl::opt< MaterializeFPImm > MaterializeFPImmInsNum("loongarch-materialize-float-imm", cl::Hidden, cl::desc("Maximum number of instructions used (including code sequence " "to generate the value and moving the value to FPR) when " "materializing floating-point immediates (default = 3)"), cl::init(MaterializeFPImm3Ins), cl::values(clEnumValN(NoMaterializeFPImm, "0", "Use constant pool"), clEnumValN(MaterializeFPImm2Ins, "2", "Materialize FP immediate within 2 instructions"), clEnumValN(MaterializeFPImm3Ins, "3", "Materialize FP immediate within 3 instructions"), clEnumValN(MaterializeFPImm4Ins, "4", "Materialize FP immediate within 4 instructions"), clEnumValN(MaterializeFPImm5Ins, "5", "Materialize FP immediate within 5 instructions"), clEnumValN(MaterializeFPImm6Ins, "6", "Materialize FP immediate within 6 instructions " "(behaves same as 5 on loongarch64)")))
static SDValue emitIntrinsicWithChainErrorMessage(SDValue Op, StringRef ErrorMsg, SelectionDAG &DAG)
const MCPhysReg ArgXRs[]
static bool CC_LoongArchAssign2GRLen(unsigned GRLen, CCState &State, CCValAssign VA1, ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, MVT ValVT2, MVT LocVT2, ISD::ArgFlagsTy ArgFlags2)
static unsigned getLoongArchWOpcode(unsigned Opcode)
const MCPhysReg ArgFPR64s[]
static MachineBasicBlock * emitPseudoCTPOP(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue performMOVGR2FR_WCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
#define IOCSRWR_CASE(NAME, NODE)
#define CRC_CASE_EXT_UNARYOP(NAME, NODE)
static SDValue lowerVECTOR_SHUFFLE_VPACKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPACKOD (if possible).
static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT, SDValue Src, const SDLoc &DL)
static SDValue isNOT(SDValue V, SelectionDAG &DAG)
static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Dispatching routine to lower various 256-bit LoongArch vector shuffles.
static SDValue lowerVECTOR_SHUFFLE_VREPLVEI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VREPLVEI (if possible).
static MachineBasicBlock * emitPseudoXVINSGR2VR(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
const MCPhysReg PreserveNoneArgGPRs[]
static void fillVector(ArrayRef< SDValue > Ops, SelectionDAG &DAG, SDLoc DL, const LoongArchSubtarget &Subtarget, SDValue &Vector, EVT ResTy)
static SDValue fillSubVectorFromBuildVector(BuildVectorSDNode *Node, SelectionDAG &DAG, SDLoc DL, const LoongArchSubtarget &Subtarget, EVT ResTy, unsigned first)
static bool isSelectPseudo(MachineInstr &MI)
static SDValue foldVMskZeroTest(SDValue LHS, SDValue RHS, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue foldBinOpIntoSelectIfProfitable(SDNode *BO, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorSplatImm(SDNode *Node, unsigned ImmOp, SelectionDAG &DAG, bool IsSigned=false)
const MCPhysReg ArgGPRs[]
static SDValue lowerVECTOR_SHUFFLE_XVPERM(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERM (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVILVL(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVILVL (if possible).
static SDValue performVNi128AddSubCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performFP_TO_INTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VPERMI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VPERMI (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVEXTRINS(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVEXTRINS (if possible).
static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, int NumOp, unsigned ExtOpc=ISD::ANY_EXTEND)
static void replaceVecCondBranchResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned ResOp)
#define ASRT_LE_GT_CASE(NAME)
static SDValue lowerVECTOR_SHUFFLE_XVPACKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPACKEV (if possible).
static SDValue matchDeinterleaveBuildVector(SDValue N, unsigned &StartIndex)
static SDValue performBR_CCCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static void computeZeroableShuffleElements(ArrayRef< int > Mask, SDValue V1, SDValue V2, APInt &KnownUndef, APInt &KnownZero)
Compute whether each element of a shuffle is zeroable.
static SDValue combineFP_ROUND(SDValue N, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static bool isCheapVNi128VectorOperand(SDValue V, MVT PartVT, SelectionDAG &DAG)
static SDValue performCONCAT_VECTORSCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue widenShuffleMask(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
static bool canonicalizeShuffleVectorByLane(const SDLoc &DL, MutableArrayRef< int > Mask, MVT VT, SDValue &V1, SDValue &V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Shuffle vectors by lane to generate more optimized instructions.
static SDValue combineSubOfBoolean(SDNode *N, SelectionDAG &DAG)
static SDValue lowerVECTOR_SHUFFLE_XVILVH(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVILVH (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVSHUF(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVSHUF (if possible).
static void replaceCMP_XCHG_128Results(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG)
static SDValue lowerVectorPickVE2GR(SDNode *N, SelectionDAG &DAG, unsigned ResOp)
static SDValue performBITREV_WCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static bool isVectorRegisterVT(EVT VT, SelectionDAG &DAG)
static SDValue matchHalfOf128BitLanes(SDValue N, bool isLow)
#define IOCSRRD_CASE(NAME, NODE)
static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2, ArrayRef< int > Mask)
Attempts to match vector shuffle as byte rotation.
static SDValue lowerVECTOR_SHUFFLE_XVREPLVE0(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVREPLVE0 (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVPICKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPICKEV (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVREPLVEI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVREPLVEI (if possible).
static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode, unsigned ScalarSizeInBits, ArrayRef< int > Mask, int MaskOffset, const APInt &Zeroable)
Attempts to match a shuffle mask against the VBSLL, VBSRL, VSLLI and VSRLI instruction.
static SDValue lowerVECTOR_SHUFFLE_VILVL(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VILVL (if possible).
static SDValue performMULCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorBitClearImm(SDNode *Node, SelectionDAG &DAG)
static MachineBasicBlock * emitBuildPairF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLEAsLanePermuteAndShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE as lane permute and then shuffle (if possible).
static bool hasOnlyVectorUsers(LoadSDNode *Ld, SelectionDAG &DAG)
static void replaceINTRINSIC_WO_CHAINResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
#define CSR_CASE(ID)
static SDValue MergeBlocksConvert(SDNode *N, SelectionDAG &DAG, unsigned Opcode, unsigned BlockBits)
static SDValue lowerVECTOR_SHUFFLE_VPICKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPICKOD (if possible).
static Intrinsic::ID getIntrinsicForMaskedAtomicRMWBinOp(unsigned GRLen, AtomicRMWInst::BinOp BinOp)
static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, ISD::CondCode &CC, SelectionDAG &DAG)
static Register allocateArgGPR(CCState &State)
static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT, ArrayRef< int > Mask, SmallVectorImpl< int > &RepeatedMask)
Test whether a shuffle mask is equivalent within each sub-lane.
static SDValue convertRMEncoding(SelectionDAG &DAG, const SDLoc &DL, MVT GRLenVT, SDValue RMValue)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
static constexpr MCPhysReg SPReg
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool inRange(const MCExpr *Expr, int64_t MinValue, int64_t MaxValue, bool AllowSymbol=false)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static bool isSequentialOrUndefInRange(ArrayRef< int > Mask, unsigned Pos, unsigned Size, int Low, int Step=1)
Return true if every element in Mask, beginning from position Pos and ending in Pos + Size,...
Value * RHS
Value * LHS
bool isZero() const
Definition APFloat.h:1608
APInt bitcastToAPInt() const
Definition APFloat.h:1504
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
An instruction that atomically checks whether a specified value is in a memory location,...
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
an instruction that atomically reads a memory location, combines it with another value,...
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ UMax
*p = old >unsigned v ? old : v
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
Value * getPointerOperand()
bool isFloatingPointOperation() const
BinOp getOperation() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT, LocInfo HTP, unsigned ExtraInfo=0)
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
unsigned getValNo() const
static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
const APFloat & getValueAPF() const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
int64_t getSExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:504
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:127
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
iterator_range< arg_iterator > args()
Definition Function.h:886
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
Argument * getArg(unsigned i) const
Definition Function.h:880
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
bool isDSOLocal() const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
void setIncomingIndirectArg(unsigned ArgIndex, Register Reg)
Register getIncomingIndirectArg(unsigned ArgIndex) const
bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const override
Return true if result of the specified node is used by a return node only.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const override
Hooks for building estimates in place of slower divisions and square roots.
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
This method can be implemented by targets that want to expose additional information about sign bits ...
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
TargetLowering::AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *CI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
bool isFPImmCheapInGPR(const APFloat &Imm, EVT VT) const
Returns true if building Imm in a GPR and moving it to a float register is cheaper than loading it fr...
Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const override
Perform a masked cmpxchg using a target-specific intrinsic.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
std::pair< bool, uint64_t > isImmVLDILegalForMode1(const APInt &SplatValue, const unsigned SplatBitSize) const
Check if a constant splat can be generated using [x]vldi, where imm[12] is 1.
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this function.
SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const override
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
bool isExtractVecEltCheap(EVT VT, unsigned Index) const override
Return true if extraction of a scalar element from the given vector type at the given index is cheap.
LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const override
Determine if the target supports unaligned memory accesses.
bool isCheapToSpeculateCtlz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic ctlz.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, Align &PrefAlign) const override
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const override
Perform a masked atomicrmw using a target-specific intrinsic.
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool signExtendConstant(const ConstantInt *CI) const override
Return true if this constant should be sign extended when promoting to a larger type.
ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const override
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
TargetLowering::AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
bool isCheapToSpeculateCttz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic cttz.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
MachineBasicBlock * emitDynamicProbedAlloc(MachineInstr &MI, MachineBasicBlock *MBB) const
bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const override
Returns true if arguments should be sign-extended in lib calls.
bool shouldScalarizeBinop(SDValue VecOp) const override
Try to convert an extract element of a vector binary operation into an extract element followed by a ...
bool isFPImmVLDILegal(const APFloat &Imm, EVT VT) const
bool shouldExtendTypeInLibCall(EVT Type) const override
Returns true if arguments should be extended in lib calls.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const override
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
void emitExpandAtomicRMW(AtomicRMWInst *AI) const override
Perform a atomicrmw expansion using a target-specific way.
ISD::NodeType getExtendForAtomicCmpSwapArg() const override
Returns how the platform's atomic compare and swap expects its comparison value to be extended (ZERO_...
LoongArchTargetLowering(const TargetMachine &TM, const LoongArchSubtarget &STI)
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
bool hasAndNotCompare(SDValue Y) const override
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const override
Return a reciprocal estimate value for the input operand.
bool canMergeStoresTo(unsigned AddressSpace, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
bool hasFeature(unsigned Feature) const
Machine Value Type.
static MVT getFloatingPointVT(unsigned BitWidth)
bool is128BitVector() const
Return true if this is a 128-bit vector type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
bool is256BitVector() const
Return true if this is a 256-bit vector type.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
MVT getDoubleNumVectorElementsVT() const
MVT getHalfNumVectorElementsVT() const
Return a VT for a vector type with the same element type but half the number of elements.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
MVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void push_back(MachineInstr *MI)
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI void collectDebugValues(SmallVectorImpl< MachineInstr * > &DbgValues)
Scan instructions immediately following MI and collect any matching DBG_VALUEs.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Align getAlign() const
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
size_t use_size() const
Return the number of uses of this node.
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
uint64_t getScalarValueSizeInBits() const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
bool isSafeToSpeculativelyExecute(unsigned Opcode) const
Some opcodes may create immediate undefined behavior when used with some values (integer division-by-...
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
static LLVM_ABI bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
static LLVM_ABI bool isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
ArrayRef< int > getMask() const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
typename SuperClass::const_iterator const_iterator
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
void setMaxBytesForAlignment(unsigned MaxBytes)
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
@ Bitcast
Build the immediate as a bitcast of an integer constant with the same bits.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
std::vector< ArgListEntry > ArgListTy
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Vector Op.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
bool useTLSDESC() const
Returns true if this target uses TLS Descriptors.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent EVT's, which are used to parameterize some operations.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SET_ROUNDING
Set rounding mode.
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isExtVecInRegOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0...
LLVM_ABI bool isFreezeUndef(SDValue V)
Return true if the specified value is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
LLVM_ABI bool isBuildVectorAllOnes(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(SDValue V)
Return true if the specified value is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
bool isIntEqualitySetCC(CondCode Code)
Return true if this is a setcc instruction that performs an equality comparison when used with intege...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ABI getTargetABI(StringRef ABIName)
InstSeq generateInstSeq(int64_t Val)
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
Definition PtrState.h:41
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:262
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
constexpr unsigned BitWidth
std::string join_items(Sep Separator, Args &&... Items)
Joins the strings in the parameter pack Items, adding Separator between the elements....
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool is128BitVector() const
Return true if this is a 128-bit vector type.
Definition ValueTypes.h:245
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isFixedLengthVector() const
Definition ValueTypes.h:214
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
Definition ValueTypes.h:55
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool is256BitVector() const
Return true if this is a 256-bit vector type.
Definition ValueTypes.h:250
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
Align getNonZeroOrigAlign() const
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...