LLVM 24.0.0git
X86ISelLowering.cpp
Go to the documentation of this file.
1//===-- X86ISelLowering.cpp - X86 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 X86 uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86ISelLowering.h"
16#include "X86.h"
17#include "X86FrameLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86IntrinsicsInfo.h"
21#include "X86TargetMachine.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
44#include "llvm/IR/CallingConv.h"
45#include "llvm/IR/Constants.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/GlobalAlias.h"
51#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/Intrinsics.h"
55#include "llvm/MC/MCAsmInfo.h"
56#include "llvm/MC/MCContext.h"
57#include "llvm/MC/MCExpr.h"
58#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <bitset>
66#include <cctype>
67#include <list>
68#include <numeric>
69using namespace llvm;
70
71#define DEBUG_TYPE "x86-isel"
72
74 const X86Subtarget &STI)
75 : TargetLowering(TM, STI), Subtarget(STI) {
76 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
77 MVT PtrVT = Subtarget.isTarget64BitLP64() ? MVT::i64 : MVT::i32;
78
79 // Set up the TargetLowering object.
80
81 // X86 is weird. It always uses i8 for shift amounts and setcc results.
83 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
85
86 // X86 instruction cache is coherent with its data cache so we can use the
87 // default expansion to a no-op.
89
90 // For 64-bit, since we have so many registers, use the ILP scheduler.
91 // For 32-bit, use the register pressure specific scheduling.
92 // For Atom, always use ILP scheduling.
93 if (Subtarget.isAtom())
95 else if (Subtarget.is64Bit())
97 else
99 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
100 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
101
102 // Bypass expensive divides and use cheaper ones.
103 if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
104 if (Subtarget.hasSlowDivide32())
105 addBypassSlowDiv(32, 8);
106 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
107 addBypassSlowDiv(64, 32);
108 }
109
110 if (Subtarget.canUseCMPXCHG16B())
112 else if (Subtarget.canUseCMPXCHG8B())
114 else
116
117 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
118
120
121 // Set up the register classes.
122 addRegisterClass(MVT::i8, &X86::GR8RegClass);
123 addRegisterClass(MVT::i16, &X86::GR16RegClass);
124 addRegisterClass(MVT::i32, &X86::GR32RegClass);
125 if (Subtarget.is64Bit())
126 addRegisterClass(MVT::i64, &X86::GR64RegClass);
127
128 for (MVT VT : MVT::integer_valuetypes())
130
131 // We don't accept any truncstore of integer registers.
132 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
133 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
134 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
135 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
136 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
137 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
138
139 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
140
141 // SETOEQ and SETUNE require checking two conditions.
142 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
145 }
146
147 // Integer absolute.
148 if (Subtarget.canUseCMOV()) {
149 setOperationAction(ISD::ABS , MVT::i16 , Custom);
150 setOperationAction(ISD::ABS , MVT::i32 , Custom);
151 if (Subtarget.is64Bit())
152 setOperationAction(ISD::ABS , MVT::i64 , Custom);
153 }
154
155 // Absolute difference.
156 for (auto Op : {ISD::ABDS, ISD::ABDU}) {
157 setOperationAction(Op , MVT::i8 , Custom);
158 setOperationAction(Op , MVT::i16 , Custom);
159 setOperationAction(Op , MVT::i32 , Custom);
160 if (Subtarget.is64Bit())
161 setOperationAction(Op , MVT::i64 , Custom);
162 }
163
164 // Signed saturation subtraction.
168 if (Subtarget.is64Bit())
170
171 // Funnel shifts.
172 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
173 // For slow shld targets we only lower for code size.
174 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
175
176 setOperationAction(ShiftOp , MVT::i8 , Custom);
177 setOperationAction(ShiftOp , MVT::i16 , Custom);
178 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
179 if (Subtarget.is64Bit())
180 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
181 }
182
183 if (!Subtarget.useSoftFloat()) {
184 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
185 // operation.
190 // We have an algorithm for SSE2, and we turn this into a 64-bit
191 // FILD or VCVTUSI2SS/SD for other targets.
194 // We have an algorithm for SSE2->double, and we turn this into a
195 // 64-bit FILD followed by conditional FADD for other targets.
198
199 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
200 // this operation.
203 // SSE has no i16 to fp conversion, only i32. We promote in the handler
204 // to allow f80 to use i16 and f64 to use i16 with sse1 only
207 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
210 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
211 // are Legal, f80 is custom lowered.
214
215 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
216 // this operation.
218 // FIXME: This doesn't generate invalid exception when it should. PR44019.
224 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
225 // are Legal, f80 is custom lowered.
228
229 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 // conversion.
232 // FIXME: This doesn't generate invalid exception when it should. PR44019.
235 // FIXME: This doesn't generate invalid exception when it should. PR44019.
241
246
247 if (!Subtarget.is64Bit() && Subtarget.hasX87()) {
250 }
251 }
252
253 // Handle address space casts between mixed sized pointers.
256
257 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
258 if (!Subtarget.hasSSE2()) {
261 if (Subtarget.is64Bit()) {
263 // Without SSE, i64->f64 goes through memory.
265 }
266 } else if (!Subtarget.is64Bit())
268
269 // Scalar integer divide and remainder are lowered to use operations that
270 // produce two results, to match the available instructions. This exposes
271 // the two-result form to trivial CSE, which is able to combine x/y and x%y
272 // into a single instruction.
273 //
274 // Scalar integer multiply-high is also lowered to use two-result
275 // operations, to match the available instructions. However, plain multiply
276 // (low) operations are left as Legal, as there are single-result
277 // instructions for this in x86. Using the two-result multiply instructions
278 // when both high and low results are needed must be arranged by dagcombine.
279 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
286 }
287
288 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
291 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
294 }
295 if (Subtarget.is64Bit())
300
305
306 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
312 }
313
314 // Promote the i8 variants and force them on up to i32 which has a shorter
315 // encoding.
316 setOperationPromotedToType(ISD::CTTZ, MVT::i8, MVT::i32);
318 // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
319 // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
320 // promote that too.
321 setOperationPromotedToType(ISD::CTTZ, MVT::i16, MVT::i32);
323
324 if (!Subtarget.hasBMI()) {
327 if (Subtarget.is64Bit()) {
330 }
331 }
332
333 if (Subtarget.hasLZCNT()) {
334 // When promoting the i8 variants, force them to i32 for a shorter
335 // encoding.
336 setOperationPromotedToType(ISD::CTLZ, MVT::i8, MVT::i32);
338 } else {
339 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
340 if (VT == MVT::i64 && !Subtarget.is64Bit())
341 continue;
344 }
345 }
346
349 // Special handling for half-precision floating point conversions.
350 // If we don't have F16C support, then lower half float conversions
351 // into library calls.
353 Op, MVT::f32,
354 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
355 // There's never any support for operations beyond MVT::f32.
356 setOperationAction(Op, MVT::f64, Expand);
357 setOperationAction(Op, MVT::f80, Expand);
358 setOperationAction(Op, MVT::f128, Expand);
359 }
360
361 for (auto VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
364 }
365
366 for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
367 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
368 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
369 setTruncStoreAction(VT, MVT::f16, Expand);
370 setTruncStoreAction(VT, MVT::bf16, Expand);
371
374 }
375
379 if (Subtarget.is64Bit())
381 if (Subtarget.hasPOPCNT()) {
382 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
383 // popcntw is longer to encode than popcntl and also has a false dependency
384 // on the dest that popcntl hasn't had since Cannon Lake.
385 setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
386 } else {
391 }
392
393 if (Subtarget.hasBMI2()) {
394 bool SlowPDEP = Subtarget.isPDEPSlow();
395 bool SlowPEXT = Subtarget.isPEXTSlow();
398 setOperationAction(ISD::PDEP, MVT::i32, SlowPDEP ? Custom : Legal);
399 setOperationAction(ISD::PEXT, MVT::i32, SlowPEXT ? Custom : Legal);
400 if (Subtarget.is64Bit()) {
401 setOperationAction(ISD::PDEP, MVT::i64, SlowPDEP ? Custom : Legal);
402 setOperationAction(ISD::PEXT, MVT::i64, SlowPEXT ? Custom : Legal);
403 }
404 }
405
407
408 if (!Subtarget.hasMOVBE())
410
411 // X86 wants to expand cmov itself.
412 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
417 }
418 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
419 if (VT == MVT::i64 && !Subtarget.is64Bit())
420 continue;
423 }
424
426
427 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
430
432 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
433 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
437
438 // Darwin ABI issue.
439 for (auto VT : { MVT::i32, MVT::i64 }) {
440 if (VT == MVT::i64 && !Subtarget.is64Bit())
441 continue;
448 }
449
450 // 64-bit shl, sra, srl (iff 32-bit x86)
451 for (auto VT : { MVT::i32, MVT::i64 }) {
452 if (VT == MVT::i64 && !Subtarget.is64Bit())
453 continue;
457 }
458
459 if (Subtarget.hasSSEPrefetch())
461
463
464 // Expand certain atomics
465 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
473 }
474
475 if (!Subtarget.is64Bit())
477
478 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
479 // All CPUs supporting AVX will atomically load/store aligned 128-bit
480 // values, so we can emit [V]MOVAPS/[V]MOVDQA.
483 }
484
485 if (Subtarget.canUseCMPXCHG16B())
487
490
493
494 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 if (Subtarget.isTargetPS())
498 else
500
501 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
503 setOperationAction(ISD::VAEND , MVT::Other, Expand);
504 bool Is64Bit = Subtarget.is64Bit();
505 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
506 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
507
510
512
513 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516
518
519 auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
520 setOperationAction(ISD::FABS, VT, Action);
521 setOperationAction(ISD::FNEG, VT, Action);
523 setOperationAction(ISD::FREM, VT, Action);
524 setOperationAction(ISD::FMA, VT, Action);
525 setOperationAction(ISD::FMINNUM, VT, Action);
526 setOperationAction(ISD::FMAXNUM, VT, Action);
531 setOperationAction(ISD::FSIN, VT, Action);
532 setOperationAction(ISD::FCOS, VT, Action);
533 setOperationAction(ISD::FSINCOS, VT, Action);
534 setOperationAction(ISD::FTAN, VT, Action);
535 setOperationAction(ISD::FSQRT, VT, Action);
536 setOperationAction(ISD::FPOW, VT, Action);
537 setOperationAction(ISD::FPOWI, VT, Action);
538 setOperationAction(ISD::FLOG, VT, Action);
539 setOperationAction(ISD::FLOG2, VT, Action);
540 setOperationAction(ISD::FLOG10, VT, Action);
541 setOperationAction(ISD::FEXP, VT, Action);
542 setOperationAction(ISD::FEXP2, VT, Action);
543 setOperationAction(ISD::FEXP10, VT, Action);
544 setOperationAction(ISD::FCEIL, VT, Action);
545 setOperationAction(ISD::FFLOOR, VT, Action);
547 setOperationAction(ISD::FRINT, VT, Action);
548 setOperationAction(ISD::BR_CC, VT, Action);
549 setOperationAction(ISD::SETCC, VT, Action);
552 setOperationAction(ISD::FROUND, VT, Action);
554 setOperationAction(ISD::FTRUNC, VT, Action);
555 setOperationAction(ISD::FLDEXP, VT, Action);
556 setOperationAction(ISD::FFREXP, VT, Action);
558 };
559
560 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
561 // f16, f32 and f64 use SSE.
562 // Set up the FP register classes.
563 addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
564 : &X86::FR16RegClass);
565 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
566 : &X86::FR32RegClass);
567 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
568 : &X86::FR64RegClass);
569
570 // Disable f32->f64 extload as we can only generate this in one instruction
571 // under optsize. So its easier to pattern match (fpext (load)) for that
572 // case instead of needing to emit 2 instructions for extload in the
573 // non-optsize case.
574 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
575
576 for (auto VT : { MVT::f32, MVT::f64 }) {
577 // Use ANDPD to simulate FABS.
579
580 // Use XORP to simulate FNEG.
582
583 // Use ANDPD and ORPD to simulate FCOPYSIGN.
585
586 // These might be better off as horizontal vector ops.
589
590 // We don't support sin/cos/fmod
594 }
595
596 // Half type will be promoted by default.
597 setF16Action(MVT::f16, Promote);
608
638
643
648
651
652 // Lower this to MOVMSK plus an AND.
655
656 } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
657 (UseX87 || Is64Bit)) {
658 // Use SSE for f32, x87 for f64.
659 // Set up the FP register classes.
660 addRegisterClass(MVT::f32, &X86::FR32RegClass);
661 if (UseX87)
662 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
663
664 // Use ANDPS to simulate FABS.
666
667 // Use XORP to simulate FNEG.
669
670 if (UseX87)
672
673 // Use ANDPS and ORPS to simulate FCOPYSIGN.
674 if (UseX87)
677
678 // We don't support sin/cos/fmod
682
683 if (UseX87) {
684 // Always expand sin/cos functions even though x87 has an instruction.
688 }
689 } else if (UseX87) {
690 // f32 and f64 in x87.
691 // Set up the FP register classes.
692 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
693 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
694
695 for (auto VT : { MVT::f32, MVT::f64 }) {
698
699 // Always expand sin/cos functions even though x87 has an instruction.
703 }
704 }
705
706 // Expand FP32 immediates into loads from the stack, save special cases.
707 if (isTypeLegal(MVT::f32)) {
708 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
709 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
710 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
711 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
712 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
713 } else // SSE immediates.
714 addLegalFPImmediate(APFloat(+0.0f)); // xorps
715 }
716 // Expand FP64 immediates into loads from the stack, save special cases.
717 if (isTypeLegal(MVT::f64)) {
718 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
719 addLegalFPImmediate(APFloat(+0.0)); // FLD0
720 addLegalFPImmediate(APFloat(+1.0)); // FLD1
721 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
722 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
723 } else // SSE immediates.
724 addLegalFPImmediate(APFloat(+0.0)); // xorpd
725 }
726 // Support fp16 0 immediate.
727 if (isTypeLegal(MVT::f16))
728 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
729
730 // Handle constrained floating-point operations of scalar.
743
744 // We don't support FMA.
747
748 // f80 always uses X87.
749 if (UseX87) {
750 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 {
755 addLegalFPImmediate(TmpFlt); // FLD0
756 TmpFlt.changeSign();
757 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758
759 bool ignored;
760 APFloat TmpFlt2(+1.0);
762 &ignored);
763 addLegalFPImmediate(TmpFlt2); // FLD1
764 TmpFlt2.changeSign();
765 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 }
767
768 // Always expand sin/cos functions even though x87 has an instruction.
769 // clang-format off
781 // clang-format on
782
794
795 // Handle constrained floating-point operations of scalar.
802 if (isTypeLegal(MVT::f16)) {
805 } else {
807 }
808 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
809 // as Custom.
811 }
812
813 // f128 uses xmm registers, but most operations require libcalls.
814 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
815 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
816 : &X86::VR128RegClass);
817
818 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
819
830
834
835 // clang-format off
843 // clang-format on
844 // No STRICT_FSINCOS
847
850 // We need to custom handle any FP_ROUND with an f128 input, but
851 // LegalizeDAG uses the result type to know when to run a custom handler.
852 // So we have to list all legal floating point result types here.
853 if (isTypeLegal(MVT::f32)) {
856 }
857 if (isTypeLegal(MVT::f64)) {
860 }
861 if (isTypeLegal(MVT::f80)) {
865 }
866
868
869 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
870 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
871 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
872 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
873 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
874 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
875 }
876
877 // Always use a library call for pow.
878 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
879 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
880 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
881 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
882
891
892 // Some FP actions are always expanded for vector types.
893 for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
894 MVT::v4f32, MVT::v8f32, MVT::v16f32,
895 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
896 // clang-format off
910 // clang-format on
911 }
912
913 // First set operation action for all vector types to either promote
914 // (for widening) or expand (for scalarization). Then we will selectively
915 // turn on ones that can be effectively codegen'd.
955 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
956 setTruncStoreAction(InnerVT, VT, Expand);
957
960
961 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
962 // types, we have to deal with them whether we ask for Expansion or not.
963 // Setting Expand causes its own optimisation problems though, so leave
964 // them legal.
965 if (VT.getVectorElementType() == MVT::i1)
966 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
967
968 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
969 // split/scalarized right now.
970 if (VT.getVectorElementType() == MVT::f16 ||
971 VT.getVectorElementType() == MVT::bf16)
972 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
973 }
974 }
975
976 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
977 // with -msoft-float, disable use of MMX as well.
978 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
979 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
980 // No operations on x86mmx supported, everything uses intrinsics.
981 }
982
983 auto SetFPMinMaxAction = [&](MVT VT) {
992 };
993
994 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
995 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
996 : &X86::VR128RegClass);
997
998 SetFPMinMaxAction(MVT::f32);
999
1000 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
1001 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
1009
1010 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
1011 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
1013
1019 }
1020
1021 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1022 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1023 : &X86::VR128RegClass);
1024
1025 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1026 // registers cannot be used even for integer operations.
1027 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1028 : &X86::VR128RegClass);
1029 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1030 : &X86::VR128RegClass);
1031 addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1032 : &X86::VR128RegClass);
1033 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1034 : &X86::VR128RegClass);
1035 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1036 : &X86::VR128RegClass);
1037
1038 for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 })
1039 SetFPMinMaxAction(VT);
1040
1041 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
1042 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
1043 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
1044
1045 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1046 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1047 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1048 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
1049 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
1050 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
1051 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
1052 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
1053 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
1054 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1057
1058 if (!Subtarget.is64Bit()) {
1059 setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1060 setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1061 }
1062
1063 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
1064 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
1065 setOperationAction(ISD::UMULO, MVT::v2i32, Custom);
1066
1067 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
1069 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
1071
1072 setOperationAction(ISD::LRINT, MVT::v4f32, Custom);
1073 setOperationAction(ISD::LRINT, MVT::v2i32, Custom);
1074
1075 setOperationAction(ISD::AND, MVT::i128, Custom);
1076 setOperationAction(ISD::OR, MVT::i128, Custom);
1077 setOperationAction(ISD::XOR, MVT::i128, Custom);
1079
1080 if (Subtarget.hasPCLMUL()) {
1081 for (auto VT : {MVT::i64, MVT::v4i32, MVT::v2i64}) {
1084 }
1088 }
1089
1090 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1091 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1092 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1093 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1094 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1095 }
1096
1097 // SSE2 can use basic vector unrolling.
1098 // SSE41 can use PHMINPOS to perform v16i8/v8i16 minmax reductions.
1099 // Fallback to ReplaceNodeResults for vXi64 reductions on 32-bit targets.
1100 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::i64}) {
1109 }
1110
1121
1126
1127 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1133
1134 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1135 // setcc all the way to isel and prefer SETGT in some isel patterns.
1138 }
1139
1140 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
1141 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
1146
1147 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1153 }
1154
1155 for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1159
1160 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1161 continue;
1162
1165 }
1166 setF16Action(MVT::v8f16, Expand);
1167 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1168 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1169 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1170 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1171 setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1172 setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1175
1176 // Custom lower v2i64 and v2f64 selects.
1183
1190
1191 // Custom legalize these to avoid over promotion or custom promotion.
1192 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1197 }
1198
1199 // Custom lowering for saturating float to int conversions.
1200 // We handle promotion to larger result types manually.
1201 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
1202 if (VT == MVT::i64 && !Subtarget.is64Bit())
1203 continue;
1206 }
1207
1212
1215
1218
1219 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1224
1229
1230 // We want to legalize this to an f64 load rather than an i64 load on
1231 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1232 // store.
1233 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1234 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1235 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1236 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1237 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1239
1240 // Add 32-bit vector stores to help vectorization opportunities.
1241 setOperationAction(ISD::STORE, MVT::v2i16, Custom);
1243
1247 if (!Subtarget.hasAVX512())
1249
1253
1255
1272
1273 // In the customized shift lowering, the legal v4i32/v2i64 cases
1274 // in AVX2 will be recognized.
1275 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1279 if (VT == MVT::v2i64) continue;
1284 }
1285
1291 }
1292
1293 if (!Subtarget.useSoftFloat() && Subtarget.hasGFNI()) {
1298
1299 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1301 }
1302
1303 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1304 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
1305 }
1306
1307 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1308 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1309 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1310 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1311
1312 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1315 }
1317
1318 // These might be better off as horizontal vector ops.
1323 }
1324 if (Subtarget.hasNDD()) {
1325 // Enable custom lowering for scalar USUBSAT to optimize usub.sat(X,1)
1326 // with cmp+adc when NDD is available.
1331 }
1332 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1333 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1336 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1340 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1346
1348 }
1349
1350 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1351 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1352 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1353 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1354 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1355 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1356 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1357 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1358
1362
1363 // FIXME: Do we need to handle scalar-to-vector here?
1364 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1365 setOperationAction(ISD::SMULO, MVT::v2i32, Custom);
1366
1367 // We directly match byte blends in the backend as they match the VSELECT
1368 // condition form.
1370
1371 // SSE41 brings specific instructions for doing vector sign extend even in
1372 // cases where we don't have SRA.
1373 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1376 }
1377
1378 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1379 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1380 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1381 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1382 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1383 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1384 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1385 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1386 }
1387
1388 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1389 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1390 // do the pre and post work in the vector domain.
1393 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1394 // so that DAG combine doesn't try to turn it into uint_to_fp.
1397 }
1398 }
1399
1400 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1402 }
1403
1404 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1405 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1406 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1409 }
1410
1411 // XOP can efficiently perform BITREVERSE with VPPERM.
1412 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1414 }
1415
1416 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1417 bool HasInt256 = Subtarget.hasInt256();
1418
1419 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1420 : &X86::VR256RegClass);
1421 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1422 : &X86::VR256RegClass);
1423 addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1424 : &X86::VR256RegClass);
1425 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1426 : &X86::VR256RegClass);
1427 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1428 : &X86::VR256RegClass);
1429 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1430 : &X86::VR256RegClass);
1431 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1432 : &X86::VR256RegClass);
1433
1434 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1447
1449
1454 SetFPMinMaxAction(VT);
1455 }
1456
1457 setOperationAction(ISD::LRINT, MVT::v8f32, Custom);
1458 setOperationAction(ISD::LRINT, MVT::v4f64, Custom);
1459
1460 setOperationAction(ISD::AND, MVT::i256, Custom);
1461 setOperationAction(ISD::OR, MVT::i256, Custom);
1462 setOperationAction(ISD::XOR, MVT::i256, Custom);
1465
1466 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1467 // even though v8i16 is a legal type.
1468 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1469 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1470 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1471 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1475
1482
1494
1495 if (!Subtarget.hasAVX512())
1497
1498 // In the customized shift lowering, the legal v8i32/v4i64 cases
1499 // in AVX2 will be recognized.
1500 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1514 if (VT == MVT::v4i64) continue;
1519 }
1520
1521 // These types need custom splitting if their input is a 128-bit vector.
1526
1530 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1531 setOperationAction(ISD::SELECT, MVT::v16f16, Custom);
1534
1535 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1539 }
1540
1545
1546 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1551
1552 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1553 // setcc all the way to isel and prefer SETGT in some isel patterns.
1556 }
1557
1558 setOperationAction(ISD::SETCC, MVT::v4f64, Custom);
1559 setOperationAction(ISD::SETCC, MVT::v8f32, Custom);
1564
1565 if (Subtarget.hasAnyFMA()) {
1566 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1567 MVT::v2f64, MVT::v4f64 }) {
1570 }
1571 }
1572
1573 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1574 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1575 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1576 }
1577
1578 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1579 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1580 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1581 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1582
1583 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1584 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1585 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1586 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1587 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1588 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1589 setOperationAction(ISD::AVGCEILU, MVT::v16i16, HasInt256 ? Legal : Custom);
1590 setOperationAction(ISD::AVGCEILU, MVT::v32i8, HasInt256 ? Legal : Custom);
1591
1592 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1593 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1594
1595 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1596 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1597 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1598 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1599 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1600
1601 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1602 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1603 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1604 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1605 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1606 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1607 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1608 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1613
1614 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1615 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1616 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1617 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1618 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1619 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1620 }
1621
1622 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1625 }
1626
1627 if (HasInt256) {
1628 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1629 // when we have a 256bit-wide blend with immediate.
1632
1633 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1634 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1635 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1636 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1637 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1638 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1639 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1640 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1641 }
1642 }
1643
1644 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1645 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1646 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1648 }
1649
1650 // Extract subvector is special because the value type
1651 // (result) is 128-bit but the source is 256-bit wide.
1652 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1653 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1655 }
1656
1657 // Custom lower several nodes for 256-bit types.
1658 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1659 MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1669 }
1670 setF16Action(MVT::v16f16, Expand);
1671 setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1672 setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1675 setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1676 setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1677 setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1678 setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1679
1680 // Only PCLMUL required as we always unroll clmul vectors.
1681 if (Subtarget.hasPCLMUL()) {
1682 for (auto VT : {MVT::v8i32, MVT::v4i64}) {
1685 }
1686 }
1687
1688 if (HasInt256) {
1689 setOperationAction(ISD::MULHU, MVT::v4i64, Custom);
1690 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
1691
1693
1694 // Custom legalize 2x32 to get a little better code.
1697
1698 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1699 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1701
1702 // Custom PDEP/PEXT lowering to only scalarize for minsize.
1703 if (Subtarget.hasBMI2() && Subtarget.isPDEPSlow())
1704 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
1706
1707 if (Subtarget.hasBMI2() && Subtarget.isPEXTSlow())
1708 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
1710 }
1711
1712 if (Subtarget.hasGFNI()) {
1713 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1714 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1715 }
1716 }
1717
1718 if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1719 Subtarget.hasF16C()) {
1720 for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1723 }
1724 for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1727 }
1728 for (unsigned Opc :
1730 setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1731 setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1732 }
1733 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
1734 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
1735 }
1736
1737 // This block controls legalization of the mask vector sizes that are
1738 // available with AVX512. 512-bit vectors are in a separate block controlled
1739 // by useAVX512Regs.
1740 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1741 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1742 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1743 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1744 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1745 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1746
1750
1751 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1752 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1753 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1754 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1755 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1756 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1757 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1758 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1764
1765 // There is no byte sized k-register load or store without AVX512DQ.
1766 if (!Subtarget.hasDQI()) {
1767 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1768 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1769 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1770 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1771
1776 }
1777
1778 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1779 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1783 }
1784
1785 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1787
1788 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1792
1799 }
1800
1801 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1803 }
1804 if (Subtarget.hasDQI() && Subtarget.hasVLX()) {
1805 for (MVT VT : {MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1808 }
1809 }
1810
1811 // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1812 // elements. 512-bits can be disabled based on prefer-vector-width and
1813 // required-vector-width function attributes.
1814 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1815 bool HasBWI = Subtarget.hasBWI();
1816
1817 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1818 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1819 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1820 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1821 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1822 addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1823 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1824
1825 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1826 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1827 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1828 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1829 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1830 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1831 if (HasBWI)
1832 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1833 }
1834
1835 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1836 SetFPMinMaxAction(VT);
1844 }
1845 setOperationAction(ISD::LRINT, MVT::v16f32,
1846 Subtarget.hasDQI() ? Legal : Custom);
1847 setOperationAction(ISD::LRINT, MVT::v8f64,
1848 Subtarget.hasDQI() ? Legal : Custom);
1849 if (Subtarget.hasDQI())
1850 setOperationAction(ISD::LLRINT, MVT::v8f64, Legal);
1851
1852 setOperationAction(ISD::AND, MVT::i512, Custom);
1853 setOperationAction(ISD::OR, MVT::i512, Custom);
1854 setOperationAction(ISD::XOR, MVT::i512, Custom);
1855 setOperationAction(ISD::ADD, MVT::i512, Custom);
1856 setOperationAction(ISD::SUB, MVT::i512, Custom);
1857 setOperationAction(ISD::SRL, MVT::i512, Custom);
1858 setOperationAction(ISD::SHL, MVT::i512, Custom);
1859 setOperationAction(ISD::SRA, MVT::i512, Custom);
1860 setOperationAction(ISD::FSHR, MVT::i512, Custom);
1861 setOperationAction(ISD::FSHL, MVT::i512, Custom);
1862 setOperationAction(ISD::FSHR, MVT::i256, Custom);
1863 setOperationAction(ISD::FSHL, MVT::i256, Custom);
1866
1867 for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1872 }
1873
1874 for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1879 }
1880
1887
1899
1900 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1901 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1902 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1903 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1904 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1905 if (HasBWI)
1906 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1907
1908 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1909 // to 512-bit rather than use the AVX2 instructions so that we can use
1910 // k-masks.
1911 if (!Subtarget.hasVLX()) {
1912 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1913 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1916 }
1917 }
1918
1920 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1921 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
1931
1932 if (HasBWI) {
1933 // Extends from v64i1 masks to 512-bit vectors.
1937 }
1938
1939 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1952
1954 }
1955
1956 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1959 }
1960
1961 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1962 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1963 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
1964 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
1965
1966 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1967 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1968 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1969 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1970
1971 setOperationAction(ISD::MULHU, MVT::v8i64, Custom);
1972 setOperationAction(ISD::MULHS, MVT::v8i64, Custom);
1973 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1974 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1975 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1976 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1977 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1978 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1979 setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1980 setOperationAction(ISD::AVGCEILU, MVT::v64i8, HasBWI ? Legal : Custom);
1981
1982 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1983 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1984
1985 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
2003
2004 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
2005 // setcc all the way to isel and prefer SETGT in some isel patterns.
2008 }
2009
2010 setOperationAction(ISD::SETCC, MVT::v8f64, Custom);
2011 setOperationAction(ISD::SETCC, MVT::v16f32, Custom);
2016
2017 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
2026 }
2027
2028 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2029 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
2030 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
2032 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
2033 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
2034 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
2035 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
2040 }
2041
2042 setOperationAction(ISD::FSHL, MVT::v64i8, Custom);
2043 setOperationAction(ISD::FSHR, MVT::v64i8, Custom);
2044 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
2045 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
2046 setOperationAction(ISD::FSHL, MVT::v16i32, Custom);
2047 setOperationAction(ISD::FSHR, MVT::v16i32, Custom);
2048
2049 if (Subtarget.hasDQI() || Subtarget.hasFP16())
2053 setOperationAction(Opc, MVT::v8i64, Custom);
2054
2055 if (Subtarget.hasDQI()) {
2056 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
2057 }
2058
2059 if (Subtarget.hasCDI()) {
2060 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
2061 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
2063 }
2064 } // Subtarget.hasCDI()
2065
2066 if (Subtarget.hasVPOPCNTDQ()) {
2067 for (auto VT : { MVT::v16i32, MVT::v8i64 })
2070 }
2071
2072 // Extract subvector is special because the value type
2073 // (result) is 256-bit but the source is 512-bit wide.
2074 // 128-bit was made Legal under AVX1.
2075 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
2076 MVT::v16f16, MVT::v8f32, MVT::v4f64 })
2078
2079 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
2080 MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
2090 }
2091 setF16Action(MVT::v32f16, Expand);
2096 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2097 setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
2098 setOperationAction(ISD::SETCC, MVT::v32f16, Custom);
2099
2100 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
2105 }
2106 if (HasBWI) {
2107 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2110 }
2111 } else {
2112 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
2113 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
2114 }
2115
2116 if (Subtarget.hasVBMI2()) {
2117 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2120 }
2121
2122 setOperationAction(ISD::ROTL, MVT::v32i16, Legal);
2123 setOperationAction(ISD::ROTR, MVT::v32i16, Legal);
2124 }
2125
2126 // Only PCLMUL required as we always unroll clmul vectors.
2127 if (Subtarget.hasPCLMUL()) {
2128 for (auto VT : {MVT::v16i32, MVT::v8i64}) {
2131 }
2132 }
2133
2134 setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2135 setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2137 setOperationAction(ISD::FLDEXP, MVT::v32f16, Custom);
2138
2139 if (Subtarget.hasGFNI()) {
2140 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
2141 setOperationAction(ISD::CTTZ, MVT::v64i8, Custom);
2142 }
2143 }// useAVX512Regs
2144
2145 if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
2146 for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
2147 MVT::v4i64}) {
2150 }
2151
2152 setOperationAction(ISD::ROTL, MVT::v16i16, Legal);
2153 setOperationAction(ISD::ROTR, MVT::v16i16, Legal);
2154 setOperationAction(ISD::ROTL, MVT::v8i16, Legal);
2155 setOperationAction(ISD::ROTR, MVT::v8i16, Legal);
2156 }
2157
2158 // This block controls legalization for operations that don't have
2159 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2160 // narrower widths.
2161 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2162 for (MVT VT : {MVT::f16, MVT::f32, MVT::f64, MVT::v8f16, MVT::v4f32,
2163 MVT::v2f64, MVT::v16f16, MVT::v8f32, MVT::v4f64})
2165
2166 // These operations are handled on non-VLX by artificially widening in
2167 // isel patterns.
2171
2172 if (Subtarget.hasDQI()) {
2173 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2174 // v2f32 UINT_TO_FP is already custom under SSE2.
2177 "Unexpected operation action!");
2178 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2183 }
2184
2185 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2191 }
2192
2193 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2196 }
2197
2198 // Custom legalize 2x32 to get a little better code.
2201
2202 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2203 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2205
2206 if (Subtarget.hasDQI()) {
2210 setOperationAction(Opc, MVT::v2i64, Custom);
2211 setOperationAction(Opc, MVT::v4i64, Custom);
2212 }
2213 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2214 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2215
2216 // MULHS is only a win when the low multiply can use vpmullq; non-VLX
2217 // targets handle VPMULLQ by implicit widening.
2218 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
2219 }
2220
2221 if (Subtarget.hasCDI()) {
2222 for (auto VT : {MVT::i256, MVT::i512}) {
2223 if (VT == MVT::i512 && !Subtarget.useAVX512Regs())
2224 continue;
2229 }
2230 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2232 }
2233 } // Subtarget.hasCDI()
2234
2235 if (Subtarget.hasVPOPCNTDQ()) {
2236 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
2239 }
2240
2241 // We can try to convert vectors to different sizes to leverage legal
2242 // `vpcompress` cases. So we mark these supported vector sizes as Custom and
2243 // then specialize to Legal below.
2244 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2245 MVT::v4f64, MVT::v2i64, MVT::v2f64, MVT::v16i8, MVT::v8i16,
2246 MVT::v16i16, MVT::v8i8})
2248
2249 // Legal vpcompress depends on various AVX512 extensions.
2250 // Legal in AVX512F
2251 for (MVT VT : {MVT::v16i32, MVT::v16f32, MVT::v8i64, MVT::v8f64})
2253
2254 // Legal in AVX512F + AVX512VL
2255 if (Subtarget.hasVLX())
2256 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2257 MVT::v4f64, MVT::v2i64, MVT::v2f64})
2259
2260 // Legal in AVX512F + AVX512VBMI2
2261 if (Subtarget.hasVBMI2())
2262 for (MVT VT : {MVT::v32i16, MVT::v64i8})
2264
2265 // Legal in AVX512F + AVX512VL + AVX512VBMI2
2266 if (Subtarget.hasVBMI2() && Subtarget.hasVLX())
2267 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v32i8, MVT::v16i16})
2269 }
2270
2271 // This block control legalization of v32i1/v64i1 which are available with
2272 // AVX512BW..
2273 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2274 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
2275 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
2276
2277 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2288 }
2289
2290 for (auto VT : { MVT::v16i1, MVT::v32i1 })
2292
2293 // Extends from v32i1 masks to 256-bit vectors.
2297
2298 for (auto VT : {MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16,
2299 MVT::v16f16, MVT::v8f16, MVT::v16bf16, MVT::v8bf16}) {
2300 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
2301 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2302 }
2303
2304 // These operations are handled on non-VLX by artificially widening in
2305 // isel patterns.
2306 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2307
2308 if (Subtarget.hasBITALG()) {
2309 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2311 }
2312
2313 if (Subtarget.hasBMM()) {
2318
2319 for (auto VT : {MVT::v16i8, MVT::v32i8, MVT::v64i8})
2321 }
2322 }
2323
2324 if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2325 auto setGroup = [&] (MVT VT) {
2332
2345
2347
2350
2355
2361
2365 };
2366
2367 // AVX512_FP16 scalar operations
2368 setGroup(MVT::f16);
2369 SetFPMinMaxAction(MVT::f16);
2383
2386
2387 if (Subtarget.useAVX512Regs()) {
2388 setGroup(MVT::v32f16);
2394 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Legal);
2401
2406 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i8, MVT::v32i16);
2408 MVT::v32i16);
2409 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i8, MVT::v32i16);
2411 MVT::v32i16);
2412 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i1, MVT::v32i16);
2414 MVT::v32i16);
2415 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i1, MVT::v32i16);
2417 MVT::v32i16);
2418
2422
2423 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Legal);
2424 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2425
2426 SetFPMinMaxAction(MVT::v32f16);
2427 setOperationAction(ISD::LRINT, MVT::v32f16, Legal);
2428 setOperationAction(ISD::LLRINT, MVT::v8f16, Legal);
2429 }
2430
2435
2436 // Without VLX, these are widened to 512-bit compares during isel.
2437 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
2438 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
2439
2440 // Without VLX, v8f16/v16f16 are widened to 512-bit ops during isel.
2441 for (auto VT : {MVT::f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
2442 for (unsigned Opc :
2445
2446 if (Subtarget.hasVLX()) {
2447 setGroup(MVT::v8f16);
2448 setGroup(MVT::v16f16);
2449
2460
2467
2468 // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2471
2475
2476 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2477 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2478 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2479 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2480
2481 // Need to custom widen these to prevent scalarization.
2482 setOperationAction(ISD::LOAD, MVT::v4f16, Custom);
2483 setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2484
2485 SetFPMinMaxAction(MVT::v8f16);
2486 SetFPMinMaxAction(MVT::v16f16);
2487
2488 setOperationAction(ISD::LRINT, MVT::v8f16, Legal);
2489 setOperationAction(ISD::LRINT, MVT::v16f16, Legal);
2490 }
2491 }
2492
2493 // Keep v8bf16 legal with AVX even without native bf16 instructions so that
2494 // f32-to-bf16 conversions can be expanded in the vector domain.
2495 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
2496 addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2497 : &X86::VR128RegClass);
2498 if (Subtarget.hasAVXNECONVERT() || Subtarget.hasBWI()) {
2499 addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512()
2500 ? &X86::VR256XRegClass
2501 : &X86::VR256RegClass);
2502 addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2503 }
2504 // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2505 // provide the method to promote BUILD_VECTOR. Set the operation action
2506 // Custom to do the customization later.
2508 for (MVT VT : {MVT::v8bf16, MVT::v16bf16}) {
2509 if (!isTypeLegal(VT))
2510 continue;
2511 setF16Action(VT, Expand);
2512 if (!Subtarget.hasBF16())
2519 for (unsigned Opc :
2524 VT.changeVectorElementType(MVT::f32));
2526 }
2528 }
2529
2530 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI() &&
2531 Subtarget.useAVX512Regs()) {
2532 addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2533 setF16Action(MVT::v32bf16, Expand);
2538 setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2539
2540 if (Subtarget.hasBF16()) {
2541 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
2544 setOperationPromotedToType(Opc, MVT::v32bf16, MVT::v32f32);
2545 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2546 } else {
2547 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2548 setOperationAction(Opc, MVT::v32bf16, Expand);
2549 }
2550 }
2551
2552 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX10_2()) {
2553 for (MVT VT : {MVT::v8i8, MVT::v16i8, MVT::v32i8}) {
2556 }
2561 for (MVT VT : {MVT::i32, MVT::i64, MVT::v4i32, MVT::v8i32, MVT::v16i32,
2562 MVT::v2i64, MVT::v4i64}) {
2563 if (VT == MVT::i64 && !Subtarget.is64Bit())
2564 continue;
2567 }
2568
2569 // Lower scalar bf16 arithmetic by widening to a vector op and extracting
2570 // the low element.
2571 setOperationAction(ISD::FADD, MVT::bf16, Custom);
2572 setOperationAction(ISD::FSUB, MVT::bf16, Custom);
2573 setOperationAction(ISD::FMUL, MVT::bf16, Custom);
2574 setOperationAction(ISD::FDIV, MVT::bf16, Custom);
2576 setOperationAction(ISD::FMA, MVT::bf16, Custom);
2577
2579
2580 if (Subtarget.useAVX512Regs()) {
2581 setOperationAction(ISD::FADD, MVT::v32bf16, Legal);
2582 setOperationAction(ISD::FSUB, MVT::v32bf16, Legal);
2583 setOperationAction(ISD::FMUL, MVT::v32bf16, Legal);
2584 setOperationAction(ISD::FDIV, MVT::v32bf16, Legal);
2585 setOperationAction(ISD::FSQRT, MVT::v32bf16, Legal);
2586 setOperationAction(ISD::FMA, MVT::v32bf16, Legal);
2587 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2588 SetFPMinMaxAction(MVT::v32bf16);
2589
2591 }
2592
2593 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2602 SetFPMinMaxAction(VT);
2603 }
2604 for (auto VT : {MVT::f16, MVT::f32, MVT::f64}) {
2607 }
2608 }
2609
2610 // Partial reductions that map onto the dot product instructions:
2611 // vpdpbusd / vpdpwssd (AVX512-VNNI, AVX-VNNI)
2612 // vpdpbssd / vpdpbuud (AVX-VNNI-INT8, AVX10.2)
2613 // vpdpwsud / vpdpwuud (AVX-VNNI-INT16, AVX10.2)
2614 // vdpbf16ps (AVX512-BF16)
2615 // vdpphps (AVX10.2)
2616 // 512-bit shapes are split in two when only the VEX encoding is available.
2617 if (!Subtarget.useSoftFloat()) {
2618 bool HasVNNI = Subtarget.hasVNNI() || Subtarget.hasAVXVNNI();
2619 bool HasVNNIINT8 = Subtarget.hasAVXVNNIINT8() || Subtarget.hasAVX10_2();
2620 bool HasVNNIINT16 = Subtarget.hasAVXVNNIINT16() || Subtarget.hasAVX10_2();
2621 for (MVT AccVT : {MVT::v4i32, MVT::v8i32, MVT::v16i32}) {
2622 if (AccVT == MVT::v16i32 && !Subtarget.useAVX512Regs())
2623 break;
2624 unsigned NumElts = AccVT.getVectorNumElements();
2625 MVT I8VT = MVT::getVectorVT(MVT::i8, NumElts * 4);
2626 MVT I16VT = MVT::getVectorVT(MVT::i16, NumElts * 2);
2627 MVT F32VT = MVT::getVectorVT(MVT::f32, NumElts);
2628 if (HasVNNI) {
2630 Custom);
2632 Custom);
2633 }
2634 if (HasVNNIINT8)
2637 Custom);
2638 if (HasVNNIINT16)
2641 Custom);
2642 if (Subtarget.hasBF16())
2644 MVT::getVectorVT(MVT::bf16, NumElts * 2),
2645 Custom);
2646 if (Subtarget.hasAVX10_2())
2648 MVT::getVectorVT(MVT::f16, NumElts * 2),
2649 Custom);
2650 }
2651 }
2652
2653 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2654 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
2655 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2656 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2657 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
2658 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2659
2660 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
2661 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2662 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2663 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
2664 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2665
2666 if (Subtarget.hasBWI()) {
2667 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
2668 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
2669 }
2670
2671 if (Subtarget.hasFP16()) {
2672 // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2681 // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2690 // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2695 // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2700 }
2701 }
2702
2703 if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2704 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2705 }
2706
2707 // We want to custom lower some of our intrinsics.
2711 if (!Subtarget.is64Bit()) {
2713 }
2714
2715 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2716 // handle type legalization for these operations here.
2717 //
2718 // FIXME: We really should do custom legalization for addition and
2719 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
2720 // than generic legalization for 64-bit multiplication-with-overflow, though.
2721 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2722 if (VT == MVT::i64 && !Subtarget.is64Bit())
2723 continue;
2724 // Add/Sub/Mul with overflow operations are custom lowered.
2731
2732 // Support carry in as value rather than glue.
2738 }
2739
2740 // Combine sin / cos into _sincos_stret if it is available.
2743
2744 // The Win64 C ABI passes i128 by reference and returns it in XMM0. The
2745 // libcalls for i128 division, remainder and floating point conversions are
2746 // compiled with that ABI wherever it is the default C convention (Windows and
2747 // UEFI), so lower them accordingly there.
2748 if (Subtarget.isCallingConvWin64(CallingConv::C)) {
2749 setOperationAction(ISD::SDIV, MVT::i128, Custom);
2750 setOperationAction(ISD::UDIV, MVT::i128, Custom);
2751 setOperationAction(ISD::SREM, MVT::i128, Custom);
2752 setOperationAction(ISD::UREM, MVT::i128, Custom);
2761 }
2762
2763 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2764 // is. We should promote the value to 64-bits to solve this.
2765 // This is what the CRT headers do - `fmodf` is an inline header
2766 // function casting to f64 and calling `fmod`.
2767 if (Subtarget.is32Bit() &&
2768 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2769 // clang-format off
2770 for (ISD::NodeType Op :
2788 // TODO: Add ISD:::STRICT_FMODF too once implemented.
2789 ISD::FMODF})
2790 if (isOperationExpandOrLibCall(Op, MVT::f32))
2791 setOperationAction(Op, MVT::f32, Promote);
2792 // clang-format on
2793
2794 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
2795 // it, but it's just a wrapper around ldexp.
2796 if (Subtarget.isOSWindows()) {
2798 if (isOperationExpand(Op, MVT::f32))
2799 setOperationAction(Op, MVT::f32, Promote);
2800 }
2801
2802 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f16, MVT::i16);
2803 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f32, MVT::i32);
2804 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f64, MVT::i64);
2805
2806 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f16, MVT::i16);
2807 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f32, MVT::i32);
2808 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f64, MVT::i64);
2809
2810 // We have target-specific dag combine patterns for the following nodes:
2822 ISD::SHL,
2823 ISD::SRA,
2824 ISD::SRL,
2825 ISD::OR,
2826 ISD::AND,
2832 ISD::ADD,
2835 ISD::FADD,
2836 ISD::FSUB,
2837 ISD::FNEG,
2838 ISD::FMA,
2844 ISD::SUB,
2846 ISD::LOAD,
2847 ISD::LRINT,
2849 ISD::MLOAD,
2850 ISD::STORE,
2871 ISD::SETCC,
2872 ISD::MUL,
2873 ISD::UDIV,
2874 ISD::SDIV,
2875 ISD::UREM,
2876 ISD::SREM,
2881 ISD::XOR,
2889 ISD::ROTL,
2890 ISD::ROTR,
2891 ISD::FSHL,
2892 ISD::FSHR,
2896
2897 computeRegisterProperties(Subtarget.getRegisterInfo());
2898
2899 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2901 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2903 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2905
2906 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2907 // that needs to benchmarked and balanced with the potential use of vector
2908 // load/store types (PR33329, PR33914).
2911
2912 // Default loop alignment, which can be overridden by -align-loops.
2914
2915 // An out-of-order CPU can speculatively execute past a predictable branch,
2916 // but a conditional move could be stalled by an expensive earlier operation.
2917 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2918 EnableExtLdPromotion = true;
2920
2922
2923 // Default to having -disable-strictnode-mutation on
2924 IsStrictFPEnabled = true;
2925}
2926
2927// This has so far only been implemented for 64-bit MachO.
2929 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2930}
2931
2933 // Currently only MSVC CRTs mix the frame pointer into the stack guard value.
2934 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2935}
2936
2938 const SDLoc &DL) const {
2939 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2940 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2941 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2942 return SDValue(Node, 0);
2943}
2944
2947 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2948 !Subtarget.hasBWI())
2949 return TypeSplitVector;
2950
2951 // Since v8f16 is legal, widen anything over v4f16.
2952 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2953 VT.getVectorNumElements() <= 4 && !Subtarget.hasF16C() &&
2954 VT.getVectorElementType() == MVT::f16)
2955 return TypeSplitVector;
2956
2957 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2958 VT.getVectorElementType() != MVT::i1)
2959 return TypeWidenVector;
2960
2962}
2963
2965 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
2966 const LibcallLoweringInfo *libcallLowering) const {
2967 return X86::createFastISel(funcInfo, libInfo, libcallLowering);
2968}
2969
2970//===----------------------------------------------------------------------===//
2971// Other Lowering Hooks
2972//===----------------------------------------------------------------------===//
2973
2975 bool AssumeSingleUse, bool IgnoreAlignment) {
2976 if (!AssumeSingleUse && !Op.hasOneUse())
2977 return false;
2978 if (!ISD::isNormalLoad(Op.getNode()))
2979 return false;
2980
2981 // If this is an unaligned vector, make sure the target supports folding it.
2982 auto *Ld = cast<LoadSDNode>(Op.getNode());
2983 if (!IgnoreAlignment && !Subtarget.hasAVX() &&
2984 !Subtarget.hasSSEUnalignedMem() && Ld->getValueSizeInBits(0) == 128 &&
2985 Ld->getAlign() < Align(16))
2986 return false;
2987
2988 // TODO: If this is a non-temporal load and the target has an instruction
2989 // for it, it should not be folded. See "useNonTemporalLoad()".
2990
2991 return true;
2992}
2993
2995 const X86Subtarget &Subtarget,
2996 bool AssumeSingleUse) {
2997 assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2998 if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2999 return false;
3000
3001 // We can not replace a wide volatile load with a broadcast-from-memory,
3002 // because that would narrow the load, which isn't legal for volatiles.
3003 auto *Ld = cast<LoadSDNode>(Op.getNode());
3004 return !Ld->isVolatile() ||
3005 Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
3006}
3007
3009 if (!Op.hasOneUse())
3010 return false;
3011 // Peek through (oneuse) bitcast users
3012 SDNode *User = *Op->user_begin();
3013 while (User->getOpcode() == ISD::BITCAST) {
3014 if (!User->hasOneUse())
3015 return false;
3016 User = *User->user_begin();
3017 }
3018 return ISD::isNormalStore(User) || User->getOpcode() == ISD::ATOMIC_STORE;
3019}
3020
3022 if (Op.hasOneUse()) {
3023 unsigned Opcode = Op.getNode()->user_begin()->getOpcode();
3024 return (ISD::ZERO_EXTEND == Opcode);
3025 }
3026 return false;
3027}
3028
3029// Return true if its cheap to bitcast this to a scalar integer type on a GPR.
3031 if (peekThroughBitcasts(Op).getValueType().isScalarInteger())
3032 return true;
3034 return true;
3035 return false;
3036}
3037
3038// Return true if its cheap to bitcast this to a vector type.
3040 const X86Subtarget &Subtarget) {
3041 if (peekThroughBitcasts(Op).getValueType().isVector())
3042 return true;
3044 return true;
3045
3046 EVT VT = Op.getValueType();
3047 unsigned Opcode = Op.getOpcode();
3048 if ((VT == MVT::i128 || VT == MVT::i256 || VT == MVT::i512) &&
3049 DAG.getTargetLoweringInfo().getOperationAction(Opcode, VT) ==
3051 // Check for larger than legal scalar integer ops that might have been
3052 // custom lowered to vector instruction.
3053 switch (Opcode) {
3054 case ISD::BITREVERSE:
3055 return true;
3056 case ISD::SHL:
3057 case ISD::SRL:
3058 case ISD::SRA:
3059 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget);
3060 case ISD::AND:
3061 case ISD::OR:
3062 case ISD::XOR:
3063 case ISD::ADD:
3064 case ISD::SUB:
3065 case ISD::FSHL:
3066 case ISD::FSHR:
3067 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget) &&
3068 mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget);
3069 case ISD::SELECT:
3070 return mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget) &&
3071 mayFoldIntoVector(Op.getOperand(2), DAG, Subtarget);
3072 }
3073 }
3074 return X86::mayFoldLoad(Op, Subtarget, /*AssumeSingleUse=*/true,
3075 /*IgnoreAlignment=*/true);
3076}
3077
3078static bool isLogicOp(unsigned Opcode) {
3079 // TODO: Add support for X86ISD::FAND/FOR/FXOR/FANDN with test coverage.
3080 return ISD::isBitwiseLogicOp(Opcode) || X86ISD::ANDNP == Opcode;
3081}
3082
3083static bool isTargetShuffle(unsigned Opcode) {
3084 switch(Opcode) {
3085 default: return false;
3086 case X86ISD::BLENDI:
3087 case X86ISD::PSHUFB:
3088 case X86ISD::PSHUFD:
3089 case X86ISD::PSHUFHW:
3090 case X86ISD::PSHUFLW:
3091 case X86ISD::SHUFP:
3092 case X86ISD::INSERTPS:
3093 case X86ISD::EXTRQI:
3094 case X86ISD::INSERTQI:
3095 case X86ISD::VALIGN:
3096 case X86ISD::PALIGNR:
3097 case X86ISD::VSHLDQ:
3098 case X86ISD::VSRLDQ:
3099 case X86ISD::MOVLHPS:
3100 case X86ISD::MOVHLPS:
3101 case X86ISD::MOVSHDUP:
3102 case X86ISD::MOVSLDUP:
3103 case X86ISD::MOVDDUP:
3104 case X86ISD::MOVSS:
3105 case X86ISD::MOVSD:
3106 case X86ISD::MOVSH:
3107 case X86ISD::UNPCKL:
3108 case X86ISD::UNPCKH:
3109 case X86ISD::VBROADCAST:
3110 case X86ISD::VPERMILPI:
3111 case X86ISD::VPERMILPV:
3112 case X86ISD::VPERM2X128:
3113 case X86ISD::SHUF128:
3114 case X86ISD::VPERMIL2:
3115 case X86ISD::VPERMI:
3116 case X86ISD::VPPERM:
3117 case X86ISD::VPERMV:
3118 case X86ISD::VPERMV3:
3119 case X86ISD::VZEXT_MOVL:
3120 case X86ISD::COMPRESS:
3121 case X86ISD::EXPAND:
3122 return true;
3123 }
3124}
3125
3126static bool isTargetShuffleVariableMask(unsigned Opcode) {
3127 switch (Opcode) {
3128 default: return false;
3129 // Target Shuffles.
3130 case X86ISD::PSHUFB:
3131 case X86ISD::VPERMILPV:
3132 case X86ISD::VPERMIL2:
3133 case X86ISD::VPPERM:
3134 case X86ISD::VPERMV:
3135 case X86ISD::VPERMV3:
3136 return true;
3137 // 'Faux' Target Shuffles.
3138 case ISD::OR:
3139 case ISD::AND:
3140 case X86ISD::ANDNP:
3141 return true;
3142 }
3143}
3144
3147 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3149 int ReturnAddrIndex = FuncInfo->getRAIndex();
3150
3151 if (ReturnAddrIndex == 0) {
3152 // Set up a frame object for the return address.
3153 unsigned SlotSize = RegInfo->getSlotSize();
3154 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
3155 -(int64_t)SlotSize,
3156 false);
3157 FuncInfo->setRAIndex(ReturnAddrIndex);
3158 }
3159
3160 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3161}
3162
3164 bool HasSymbolicDisplacement) {
3165 // Offset should fit into 32 bit immediate field.
3166 if (!isInt<32>(Offset))
3167 return false;
3168
3169 // If we don't have a symbolic displacement - we don't have any extra
3170 // restrictions.
3171 if (!HasSymbolicDisplacement)
3172 return true;
3173
3174 // We can fold large offsets in the large code model because we always use
3175 // 64-bit offsets.
3176 if (CM == CodeModel::Large)
3177 return true;
3178
3179 // For kernel code model we know that all object resist in the negative half
3180 // of 32bits address space. We may not accept negative offsets, since they may
3181 // be just off and we may accept pretty large positive ones.
3182 if (CM == CodeModel::Kernel)
3183 return Offset >= 0;
3184
3185 // For other non-large code models we assume that latest small object is 16MB
3186 // before end of 31 bits boundary. We may also accept pretty large negative
3187 // constants knowing that all objects are in the positive half of address
3188 // space.
3189 return Offset < 16 * 1024 * 1024;
3190}
3191
3192/// Return true if the condition is an signed comparison operation.
3193static bool isX86CCSigned(X86::CondCode X86CC) {
3194 switch (X86CC) {
3195 default:
3196 llvm_unreachable("Invalid integer condition!");
3197 case X86::COND_E:
3198 case X86::COND_NE:
3199 case X86::COND_B:
3200 case X86::COND_A:
3201 case X86::COND_BE:
3202 case X86::COND_AE:
3203 return false;
3204 case X86::COND_G:
3205 case X86::COND_GE:
3206 case X86::COND_L:
3207 case X86::COND_LE:
3208 return true;
3209 }
3210}
3211
3213 switch (SetCCOpcode) {
3214 // clang-format off
3215 default: llvm_unreachable("Invalid integer condition!");
3216 case ISD::SETEQ: return X86::COND_E;
3217 case ISD::SETGT: return X86::COND_G;
3218 case ISD::SETGE: return X86::COND_GE;
3219 case ISD::SETLT: return X86::COND_L;
3220 case ISD::SETLE: return X86::COND_LE;
3221 case ISD::SETNE: return X86::COND_NE;
3222 case ISD::SETULT: return X86::COND_B;
3223 case ISD::SETUGT: return X86::COND_A;
3224 case ISD::SETULE: return X86::COND_BE;
3225 case ISD::SETUGE: return X86::COND_AE;
3226 // clang-format on
3227 }
3228}
3229
3230/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3231/// condition code, returning the condition code and the LHS/RHS of the
3232/// comparison to make.
3234 bool isFP, SDValue &LHS, SDValue &RHS,
3235 SelectionDAG &DAG) {
3236 if (!isFP) {
3238 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
3239 // X > -1 -> X == 0, jump !sign.
3240 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3241 return X86::COND_NS;
3242 }
3243 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
3244 // X < 0 -> X == 0, jump on sign.
3245 return X86::COND_S;
3246 }
3247 if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
3248 // X >= 0 -> X == 0, jump on !sign.
3249 return X86::COND_NS;
3250 }
3251 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
3252 // X < 1 -> X <= 0
3253 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3254 return X86::COND_LE;
3255 }
3256 }
3257
3258 return TranslateIntegerX86CC(SetCCOpcode);
3259 }
3260
3261 // First determine if it is required or is profitable to flip the operands.
3262
3263 // If LHS is a foldable load, but RHS is not, flip the condition.
3264 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3265 !ISD::isNON_EXTLoad(RHS.getNode())) {
3266 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3267 std::swap(LHS, RHS);
3268 }
3269
3270 switch (SetCCOpcode) {
3271 default: break;
3272 case ISD::SETOLT:
3273 case ISD::SETOLE:
3274 case ISD::SETUGT:
3275 case ISD::SETUGE:
3276 std::swap(LHS, RHS);
3277 break;
3278 }
3279
3280 // On a floating point condition, the flags are set as follows:
3281 // ZF PF CF op
3282 // 0 | 0 | 0 | X > Y
3283 // 0 | 0 | 1 | X < Y
3284 // 1 | 0 | 0 | X == Y
3285 // 1 | 1 | 1 | unordered
3286 switch (SetCCOpcode) {
3287 // clang-format off
3288 default: llvm_unreachable("Condcode should be pre-legalized away");
3289 case ISD::SETUEQ:
3290 case ISD::SETEQ: return X86::COND_E;
3291 case ISD::SETOLT: // flipped
3292 case ISD::SETOGT:
3293 case ISD::SETGT: return X86::COND_A;
3294 case ISD::SETOLE: // flipped
3295 case ISD::SETOGE:
3296 case ISD::SETGE: return X86::COND_AE;
3297 case ISD::SETUGT: // flipped
3298 case ISD::SETULT:
3299 case ISD::SETLT: return X86::COND_B;
3300 case ISD::SETUGE: // flipped
3301 case ISD::SETULE:
3302 case ISD::SETLE: return X86::COND_BE;
3303 case ISD::SETONE:
3304 case ISD::SETNE: return X86::COND_NE;
3305 case ISD::SETUO: return X86::COND_P;
3306 case ISD::SETO: return X86::COND_NP;
3307 case ISD::SETOEQ:
3308 case ISD::SETUNE: return X86::COND_INVALID;
3309 // clang-format on
3310 }
3311}
3312
3313/// Is there a floating point cmov for the specific X86 condition code?
3314/// Current x86 isa includes the following FP cmov instructions:
3315/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3316static bool hasFPCMov(X86::CondCode X86CC) {
3317 switch (X86CC) {
3318 default:
3319 return false;
3320 case X86::COND_B:
3321 case X86::COND_BE:
3322 case X86::COND_E:
3323 case X86::COND_P:
3324 case X86::COND_A:
3325 case X86::COND_AE:
3326 case X86::COND_NE:
3327 case X86::COND_NP:
3328 return true;
3329 }
3330}
3331
3332static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
3333 return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
3334 VT.is512BitVector();
3335}
3336
3339 MachineFunction &MF, unsigned Intrinsic) const {
3340 IntrinsicInfo Info;
3342 Info.offset = 0;
3343
3345 if (!IntrData) {
3346 switch (Intrinsic) {
3347 case Intrinsic::x86_aesenc128kl:
3348 case Intrinsic::x86_aesdec128kl:
3349 Info.opc = ISD::INTRINSIC_W_CHAIN;
3350 Info.ptrVal = I.getArgOperand(1);
3351 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3352 Info.align = Align(1);
3353 Info.flags |= MachineMemOperand::MOLoad;
3354 Infos.push_back(Info);
3355 return;
3356 case Intrinsic::x86_aesenc256kl:
3357 case Intrinsic::x86_aesdec256kl:
3358 Info.opc = ISD::INTRINSIC_W_CHAIN;
3359 Info.ptrVal = I.getArgOperand(1);
3360 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3361 Info.align = Align(1);
3362 Info.flags |= MachineMemOperand::MOLoad;
3363 Infos.push_back(Info);
3364 return;
3365 case Intrinsic::x86_aesencwide128kl:
3366 case Intrinsic::x86_aesdecwide128kl:
3367 Info.opc = ISD::INTRINSIC_W_CHAIN;
3368 Info.ptrVal = I.getArgOperand(0);
3369 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3370 Info.align = Align(1);
3371 Info.flags |= MachineMemOperand::MOLoad;
3372 Infos.push_back(Info);
3373 return;
3374 case Intrinsic::x86_aesencwide256kl:
3375 case Intrinsic::x86_aesdecwide256kl:
3376 Info.opc = ISD::INTRINSIC_W_CHAIN;
3377 Info.ptrVal = I.getArgOperand(0);
3378 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3379 Info.align = Align(1);
3380 Info.flags |= MachineMemOperand::MOLoad;
3381 Infos.push_back(Info);
3382 return;
3383 case Intrinsic::x86_cmpccxadd32:
3384 case Intrinsic::x86_cmpccxadd64:
3385 case Intrinsic::x86_atomic_bts:
3386 case Intrinsic::x86_atomic_btc:
3387 case Intrinsic::x86_atomic_btr: {
3388 Info.opc = ISD::INTRINSIC_W_CHAIN;
3389 Info.ptrVal = I.getArgOperand(0);
3390 unsigned Size = I.getType()->getScalarSizeInBits();
3391 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3392 Info.align = Align(Size);
3395 Infos.push_back(Info);
3396 return;
3397 }
3398 case Intrinsic::x86_atomic_bts_rm:
3399 case Intrinsic::x86_atomic_btc_rm:
3400 case Intrinsic::x86_atomic_btr_rm: {
3401 Info.opc = ISD::INTRINSIC_W_CHAIN;
3402 Info.ptrVal = I.getArgOperand(0);
3403 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3404 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3405 Info.align = Align(Size);
3408 Infos.push_back(Info);
3409 return;
3410 }
3411 case Intrinsic::x86_aadd32:
3412 case Intrinsic::x86_aadd64:
3413 case Intrinsic::x86_aand32:
3414 case Intrinsic::x86_aand64:
3415 case Intrinsic::x86_aor32:
3416 case Intrinsic::x86_aor64:
3417 case Intrinsic::x86_axor32:
3418 case Intrinsic::x86_axor64:
3419 case Intrinsic::x86_atomic_add_cc:
3420 case Intrinsic::x86_atomic_sub_cc:
3421 case Intrinsic::x86_atomic_or_cc:
3422 case Intrinsic::x86_atomic_and_cc:
3423 case Intrinsic::x86_atomic_xor_cc: {
3424 Info.opc = ISD::INTRINSIC_W_CHAIN;
3425 Info.ptrVal = I.getArgOperand(0);
3426 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3427 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3428 Info.align = Align(Size);
3431 Infos.push_back(Info);
3432 return;
3433 }
3434 }
3435 return;
3436 }
3437
3438 switch (IntrData->Type) {
3441 case TRUNCATE_TO_MEM_VI32: {
3442 Info.opc = ISD::INTRINSIC_VOID;
3443 Info.ptrVal = I.getArgOperand(0);
3444 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
3446 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
3447 ScalarVT = MVT::i8;
3448 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
3449 ScalarVT = MVT::i16;
3450 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
3451 ScalarVT = MVT::i32;
3452
3453 Info.memVT = VT.changeElementType(ScalarVT);
3454 Info.align = Align(1);
3455 Info.flags |= MachineMemOperand::MOStore;
3456 Infos.push_back(Info);
3457 return;
3458 }
3459 case GATHER:
3460 case GATHER_AVX2: {
3461 Info.opc = ISD::INTRINSIC_W_CHAIN;
3462 Info.ptrVal = nullptr;
3463 MVT DataVT = MVT::getVT(I.getType());
3464 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3465 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3466 IndexVT.getVectorNumElements());
3467 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3468 Info.align = Align(1);
3469 Info.flags |= MachineMemOperand::MOLoad;
3470 Infos.push_back(Info);
3471 return;
3472 }
3473 case SCATTER: {
3474 Info.opc = ISD::INTRINSIC_VOID;
3475 Info.ptrVal = nullptr;
3476 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
3477 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3478 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3479 IndexVT.getVectorNumElements());
3480 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3481 Info.align = Align(1);
3482 Info.flags |= MachineMemOperand::MOStore;
3483 Infos.push_back(Info);
3484 return;
3485 }
3486 default:
3487 return;
3488 }
3489}
3490
3491/// Returns how to materialize the specified FP immediate.
3494 bool ForCodeSize) const {
3495 for (const APFloat &FPImm : LegalFPImmediates)
3496 if (Imm.bitwiseIsEqual(FPImm))
3497 return FPImmAction::Legal;
3499}
3500
3502 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
3503 std::optional<unsigned> ByteOffset) const {
3504 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3505
3506 auto PeekThroughOneUserBitcasts = [](const SDNode *N) {
3507 while (N->getOpcode() == ISD::BITCAST && N->hasOneUse())
3508 N = *N->user_begin();
3509 return N;
3510 };
3511
3512 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3513 // relocation target a movq or addq instruction: don't let the load shrink.
3514 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3515 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3516 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3517 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3518
3519 // If this is a (1) 128-bit or wider vector load, and any use will be used by
3520 // a legal full width instruction, then the load can typically be memory
3521 // folded into that instruction, so it's probably not worth splitting the
3522 // load. Additionally, for (2) AVX vector loads with (3) multiple uses where
3523 // (4) all of those uses are extracted directly into a store, the extract +
3524 // store can be store-folded, so it's again not worth splitting.
3525 EVT VT = Load->getValueType(0);
3526 if (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) {
3527 bool FullWidthUse = false;
3528 // The extract + store folding only helps the AVX split case, which requires
3529 // multiple uses of the load.
3530 bool AllExtractStores = (VT.is256BitVector() || VT.is512BitVector()) &&
3531 !SDValue(Load, 0).hasOneUse();
3532 for (SDUse &Use : Load->uses()) {
3533 // Skip uses of the chain value. Result 0 of the node is the load value.
3534 if (Use.getResNo() != 0)
3535 continue;
3536
3537 const SDNode *User = PeekThroughOneUserBitcasts(Use.getUser());
3538
3539 // If this use is an extract + store, it's probably not worth splitting.
3540 if (AllExtractStores && User->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
3541 all_of(User->uses(), [&](const SDUse &U) {
3542 const SDNode *Inner = PeekThroughOneUserBitcasts(U.getUser());
3543 return Inner->getOpcode() == ISD::STORE;
3544 }))
3545 continue;
3546
3547 AllExtractStores = false;
3548
3549 // If any use is a full width legal/target bin op, then assume its legal
3550 // and won't split.
3551 if (isBinOp(User->getOpcode()) &&
3552 (isOperationLegal(User->getOpcode(), User->getValueType(0)) ||
3553 User->getOpcode() > ISD::BUILTIN_OP_END))
3554 FullWidthUse = true;
3555 }
3556
3557 if (AllExtractStores)
3558 return false;
3559
3560 // If we have an user that uses the full vector width, then this use is
3561 // only worth splitting if the offset isn't 0 (to avoid an
3562 // EXTRACT_SUBVECTOR) or we're loading a scalar integer.
3563 if (FullWidthUse)
3564 return (ByteOffset.value_or(0) > 0) || NewVT.isScalarInteger();
3565 }
3566
3567 return true;
3568}
3569
3570/// Returns true if it is beneficial to convert a load of a constant
3571/// to just the constant itself.
3573 Type *Ty) const {
3574 assert(Ty->isIntegerTy());
3575
3576 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3577 if (BitSize == 0 || BitSize > 64)
3578 return false;
3579 return true;
3580}
3581
3583 // If we are using XMM registers in the ABI and the condition of the select is
3584 // a floating-point compare and we have blendv or conditional move, then it is
3585 // cheaper to select instead of doing a cross-register move and creating a
3586 // load that depends on the compare result.
3587 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3588 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3589}
3590
3592 // TODO: It might be a win to ease or lift this restriction, but the generic
3593 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3594 if (VT.isVector() && Subtarget.hasAVX512())
3595 return false;
3596
3597 return true;
3598}
3599
3601 EVT) const {
3602 // With CCMP, keep and/or(setcc, setcc) trees intact so LowerSELECT can
3603 // emit them as CCMP chains rather than splitting into chained selects.
3604 return !(Subtarget.hasCCMP() && VT.isScalarInteger());
3605}
3606
3608 SDValue C) const {
3609 // TODO: We handle scalars using custom code, but generic combining could make
3610 // that unnecessary.
3611 APInt MulC;
3612 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3613 return false;
3614
3615 if (VT.isVector() && VT.getScalarSizeInBits() == 8) {
3616 // Check whether a vXi8 multiply can be decomposed into two shifts
3617 // (decomposing 2^m ± 2^n as 2^(a+b) ± 2^b). Similar to
3618 // DAGCombiner::visitMUL, consider the constant `2` decomposable as
3619 // (2^0 + 1).
3620 APInt ShiftedMulC = MulC.abs();
3621 unsigned TZeros = ShiftedMulC == 2 ? 0 : ShiftedMulC.countr_zero();
3622 ShiftedMulC.lshrInPlace(TZeros);
3623 if ((ShiftedMulC - 1).isPowerOf2() || (ShiftedMulC + 1).isPowerOf2())
3624 return true;
3625 }
3626
3627 // Find the type this will be legalized too. Otherwise we might prematurely
3628 // convert this to shl+add/sub and then still have to type legalize those ops.
3629 // Another choice would be to defer the decision for illegal types until
3630 // after type legalization. But constant splat vectors of i64 can't make it
3631 // through type legalization on 32-bit targets so we would need to special
3632 // case vXi64.
3633 while (getTypeAction(Context, VT) != TypeLegal)
3634 VT = getTypeToTransformTo(Context, VT);
3635
3636 // If vector multiply is legal, assume that's faster than shl + add/sub.
3637 // Multiply is a complex op with higher latency and lower throughput in
3638 // most implementations, sub-vXi32 vector multiplies are always fast,
3639 // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3640 // is always going to be slow.
3641 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3642 if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3643 (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3644 return false;
3645
3646 // shl+add, shl+sub, shl+add+neg
3647 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3648 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3649}
3650
3653 unsigned Index) const {
3656
3657 // Mask vectors support all subregister combinations and operations that
3658 // extract half of vector.
3659 if (ResVT.getVectorElementType() == MVT::i1) {
3660 if (Index == 0 || ((ResVT.getSizeInBits() * 2 == SrcVT.getSizeInBits()) &&
3661 (Index == ResVT.getVectorNumElements())))
3664 }
3665
3666 if (Index == 0)
3668 else if ((Index % ResVT.getVectorNumElements()) == 0)
3671}
3672
3674 unsigned Opc = VecOp.getOpcode();
3675
3676 // Assume target opcodes can't be scalarized.
3677 // TODO - do we have any exceptions?
3678 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
3679 return false;
3680
3681 // If the vector op is not supported, try to convert to scalar.
3682 EVT VecVT = VecOp.getValueType();
3684 return true;
3685
3686 // If the vector op is supported, but the scalar op is not, the transform may
3687 // not be worthwhile.
3688 EVT ScalarVT = VecVT.getScalarType();
3689 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3690}
3691
3693 bool) const {
3694 // TODO: Allow vectors?
3695 if (VT.isVector())
3696 return false;
3697 return VT.isSimple() || !isOperationExpand(Opcode, VT);
3698}
3699
3701 // Speculate cttz only if we can directly use TZCNT/CMOV, can promote to
3702 // i32/i64 or can rely on BSF passthrough value.
3703 return Subtarget.hasBMI() || Subtarget.canUseCMOV() ||
3704 Subtarget.hasBitScanPassThrough() ||
3705 (!Ty->isVectorTy() &&
3706 Ty->getScalarSizeInBits() < (Subtarget.is64Bit() ? 64u : 32u));
3707}
3708
3710 // Speculate ctlz only if we can directly use LZCNT/CMOV, or can rely on BSR
3711 // passthrough value.
3712 return Subtarget.hasLZCNT() || Subtarget.canUseCMOV() ||
3713 Subtarget.hasBitScanPassThrough();
3714}
3715
3717 // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3718 // expensive than a straight movsd. On the other hand, it's important to
3719 // shrink long double fp constant since fldt is very slow.
3720 return !Subtarget.hasSSE2() || VT == MVT::f80;
3721}
3722
3724 return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3725 (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3726}
3727
3729 const SelectionDAG &DAG,
3730 const MachineMemOperand &MMO) const {
3731 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3732 BitcastVT.getVectorElementType() == MVT::i1)
3733 return false;
3734
3735 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3736 return false;
3737
3738 if (LoadVT.isVector() && BitcastVT.isVector()) {
3739 // If both types are legal vectors, it's always ok to convert them.
3740 // Don't convert to an illegal type.
3741 if (isTypeLegal(LoadVT))
3742 return isTypeLegal(BitcastVT);
3743 }
3744
3745 // If we have a large vector type (even if illegal), don't bitcast to large
3746 // (illegal) scalar types. Better to load fewer vectors and extract.
3747 if (LoadVT.isVector() && !BitcastVT.isVector() && LoadVT.isInteger() &&
3748 BitcastVT.isInteger() && (LoadVT.getSizeInBits() % 128) == 0)
3749 return false;
3750
3751 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3752}
3753
3755 const MachineFunction &MF) const {
3756 // Do not merge to float value size (128 bytes) if no implicit
3757 // float attribute is set.
3758 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3759
3760 if (NoFloat) {
3761 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3762 return (MemVT.getSizeInBits() <= MaxIntSize);
3763 }
3764 // Make sure we don't merge greater than our preferred vector
3765 // width.
3766 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3767 return false;
3768
3769 return true;
3770}
3771
3773 return Subtarget.hasFastLZCNT();
3774}
3775
3777
3779 const Instruction &AndI) const {
3780 return true;
3781}
3782
3784 // Scalar integer and-not compares are efficiently handled by NOT+TEST (or
3785 // BMI ANDN).
3786 return Y.getValueType().isScalarInteger();
3787}
3788
3790 EVT VT = Y.getValueType();
3791
3792 if (!VT.isVector()) {
3793 if (!Subtarget.hasBMI())
3794 return false;
3795
3796 // There are only 32-bit and 64-bit forms for 'andn'.
3797 if (VT != MVT::i32 && VT != MVT::i64)
3798 return false;
3799 return !isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque();
3800 }
3801
3802 // Vector.
3803 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3804 return false;
3805
3806 if (VT == MVT::v4i32)
3807 return true;
3808
3809 return Subtarget.hasSSE2();
3810}
3811
3813 return X.getValueType().isScalarInteger(); // 'bt'
3814}
3815
3819 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3820 SelectionDAG &DAG) const {
3821 // Does baseline recommend not to perform the fold by default?
3823 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3824 return false;
3825 // For scalars this transform is always beneficial.
3826 if (X.getValueType().isScalarInteger())
3827 return true;
3828 // If all the shift amounts are identical, then transform is beneficial even
3829 // with rudimentary SSE2 shifts.
3830 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3831 return true;
3832 // If we have AVX2 with it's powerful shift operations, then it's also good.
3833 if (Subtarget.hasAVX2())
3834 return true;
3835 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3836 return NewShiftOpcode == ISD::SHL;
3837}
3838
3840 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3841 const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3842 if (!VT.isInteger())
3843 return ShiftOpc;
3844
3845 bool PreferRotate = false;
3846 if (VT.isVector()) {
3847 // For vectors, if we have rotate instruction support, then its definetly
3848 // best. Otherwise its not clear what the best so just don't make changed.
3849 PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3850 VT.getScalarType() == MVT::i64);
3851 } else if (isTypeLegal(VT)) {
3852 // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3853 // rotate unless we have a zext mask+shr. Rotates on illegal types are
3854 // expanded to shifts, so never prefer them there.
3855 PreferRotate = Subtarget.hasBMI2();
3856 if (!PreferRotate) {
3857 unsigned MaskBits =
3858 VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3859 PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3860 }
3861 }
3862
3863 if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3864 assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3865
3866 if (PreferRotate && MayTransformRotate)
3867 return ISD::ROTL;
3868
3869 // If vector we don't really get much benefit swapping around constants.
3870 // Maybe we could check if the DAG has the flipped node already in the
3871 // future.
3872 if (VT.isVector())
3873 return ShiftOpc;
3874
3875 // See if the beneficial to swap shift type.
3876 if (ShiftOpc == ISD::SHL) {
3877 // If the current setup has imm64 mask, then inverse will have
3878 // at least imm32 mask (or be zext i32 -> i64).
3879 if (VT == MVT::i64)
3880 return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3881 : ShiftOpc;
3882
3883 // We can only benefit if req at least 7-bit for the mask. We
3884 // don't want to replace shl of 1,2,3 as they can be implemented
3885 // with lea/add.
3886 return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3887 }
3888
3889 if (VT == MVT::i64)
3890 // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3891 // extremely efficient.
3892 return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3893
3894 // Keep small shifts as shl so we can generate add/lea.
3895 return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3896 }
3897
3898 // We prefer rotate for vectors of if we won't get a zext mask with SRL
3899 // (PreferRotate will be set in the latter case).
3900 if (PreferRotate || !MayTransformRotate || VT.isVector())
3901 return ShiftOpc;
3902
3903 // Non-vector type and we have a zext mask with SRL.
3904 return ISD::SRL;
3905}
3906
3908 // Prefer inc-of-add for scalars and single-element vectors, and sub-of-not
3909 // for multi-element vectors.
3910 return VT.isScalarInteger() ||
3911 (VT.isVector() && VT.getVectorElementCount().isScalar());
3912}
3913
3916 const Value *Lhs,
3917 const Value *Rhs,
3918 const Function *) const {
3919 using namespace llvm::PatternMatch;
3920 const X86Options &CLOpts = Subtarget.getCLOpts();
3921 int BaseCost = CLOpts.br_merging_base_cost;
3922 // With CCMP, branches can be merged in a more efficient way.
3923 if (BaseCost >= 0 && Subtarget.hasCCMP())
3924 BaseCost += CLOpts.br_merging_ccmp_bias;
3925 // a == b && a == c is a fast pattern on x86.
3926 if (BaseCost >= 0 && Opc == Instruction::And &&
3929 BaseCost += 1;
3930
3931 // For OR conditions with EQ comparisons, prefer splitting into branches
3932 // (unless CCMP is available). OR+EQ cannot be optimized via bitwise ops,
3933 // unlike OR+NE which becomes (P|Q)!=0. Similarly, don't split signed
3934 // comparisons (SLT, SGT) that can be optimized.
3935 if (BaseCost >= 0 && !Subtarget.hasCCMP() && Opc == Instruction::Or &&
3938 return {-1, -1, -1};
3939
3940 return {BaseCost, CLOpts.br_merging_likely_bias,
3941 CLOpts.br_merging_unlikely_bias};
3942}
3943
3945 return N->getOpcode() != ISD::FP_EXTEND;
3946}
3947
3949 const SDNode *N) const {
3950 assert(((N->getOpcode() == ISD::SHL &&
3951 N->getOperand(0).getOpcode() == ISD::SRL) ||
3952 (N->getOpcode() == ISD::SRL &&
3953 N->getOperand(0).getOpcode() == ISD::SHL)) &&
3954 "Expected shift-shift mask");
3955 // TODO: Should we always create i64 masks? Or only folded immediates?
3956 EVT VT = N->getValueType(0);
3957 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3958 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3959 // Only fold if the shift values are equal - so it folds to AND.
3960 // TODO - we should fold if either is a non-uniform vector but we don't do
3961 // the fold for non-splats yet.
3962 return N->getOperand(1) == N->getOperand(0).getOperand(1);
3963 }
3965}
3966
3968 EVT VT = Y.getValueType();
3969
3970 // For vectors, we don't have a preference, but we probably want a mask.
3971 if (VT.isVector())
3972 return false;
3973
3974 unsigned MaxWidth = Subtarget.is64Bit() ? 64 : 32;
3975 return VT.getScalarSizeInBits() <= MaxWidth;
3976}
3977
3980 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3982 !Subtarget.isOSWindows())
3985 ExpansionFactor);
3986}
3987
3989 // Any legal vector type can be splatted more efficiently than
3990 // loading/spilling from memory.
3991 return isTypeLegal(VT);
3992}
3993
3995 MVT VT = MVT::getIntegerVT(NumBits);
3996 if (isTypeLegal(VT))
3997 return VT;
3998
3999 // PMOVMSKB can handle this.
4000 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
4001 return MVT::v16i8;
4002
4003 // VPMOVMSKB can handle this.
4004 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
4005 return MVT::v32i8;
4006
4007 // TODO: Allow 64-bit type for 32-bit target.
4008 // TODO: 512-bit types should be allowed, but make sure that those
4009 // cases are handled in combineVectorSizedSetCCEquality().
4010
4012}
4013
4014/// Val is the undef sentinel value or equal to the specified value.
4015static bool isUndefOrEqual(int Val, int CmpVal) {
4016 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
4017}
4018
4019/// Return true if every element in Mask is the undef sentinel value or equal to
4020/// the specified value.
4021static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
4022 return llvm::all_of(Mask, [CmpVal](int M) {
4023 return (M == SM_SentinelUndef) || (M == CmpVal);
4024 });
4025}
4026
4027/// Return true if every element in Mask, beginning from position Pos and ending
4028/// in Pos+Size is the undef sentinel value or equal to the specified value.
4029static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
4030 unsigned Size) {
4031 return llvm::all_of(Mask.slice(Pos, Size),
4032 [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
4033}
4034
4035/// Val is either the undef or zero sentinel value.
4036static bool isUndefOrZero(int Val) {
4037 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
4038}
4039
4040/// Return true if every element in Mask, beginning from position Pos and ending
4041/// in Pos+Size is the undef sentinel value.
4042static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4043 return llvm::all_of(Mask.slice(Pos, Size), equal_to(SM_SentinelUndef));
4044}
4045
4046/// Return true if the mask creates a vector whose lower half is undefined.
4048 unsigned NumElts = Mask.size();
4049 return isUndefInRange(Mask, 0, NumElts / 2);
4050}
4051
4052/// Return true if the mask creates a vector whose upper half is undefined.
4054 unsigned NumElts = Mask.size();
4055 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
4056}
4057
4058/// Return true if Val falls within the specified range (L, H].
4059static bool isInRange(int Val, int Low, int Hi) {
4060 return (Val >= Low && Val < Hi);
4061}
4062
4063/// Return true if the value of any element in Mask falls within the specified
4064/// range (L, H].
4065static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
4066 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
4067}
4068
4069/// Return true if the value of any element in Mask is the zero sentinel value.
4070static bool isAnyZero(ArrayRef<int> Mask) {
4071 return llvm::any_of(Mask, equal_to(SM_SentinelZero));
4072}
4073
4074/// Return true if Val is undef or if its value falls within the
4075/// specified range (L, H].
4076static bool isUndefOrInRange(int Val, int Low, int Hi) {
4077 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
4078}
4079
4080/// Return true if every element in Mask is undef or if its value
4081/// falls within the specified range (L, H].
4082static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4083 return llvm::all_of(
4084 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
4085}
4086
4087/// Return true if Val is undef, zero or if its value falls within the
4088/// specified range (L, H].
4089static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4090 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
4091}
4092
4093/// Return true if every element in Mask is undef, zero or if its value
4094/// falls within the specified range (L, H].
4095static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4096 return llvm::all_of(
4097 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
4098}
4099
4100/// Return true if every element in Mask, is an in-place blend/select mask or is
4101/// undef.
4102[[maybe_unused]] static bool isBlendOrUndef(ArrayRef<int> Mask) {
4103 unsigned NumElts = Mask.size();
4104 for (auto [I, M] : enumerate(Mask))
4105 if (!isUndefOrEqual(M, I) && !isUndefOrEqual(M, I + NumElts))
4106 return false;
4107 return true;
4108}
4109
4110/// Return true if every element in Mask, beginning
4111/// from position Pos and ending in Pos + Size, falls within the specified
4112/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
4113static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
4114 unsigned Size, int Low, int Step = 1) {
4115 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4116 if (!isUndefOrEqual(Mask[i], Low))
4117 return false;
4118 return true;
4119}
4120
4121/// Return true if every element in Mask, beginning
4122/// from position Pos and ending in Pos+Size, falls within the specified
4123/// sequential range (Low, Low+Size], or is undef or is zero.
4125 unsigned Size, int Low,
4126 int Step = 1) {
4127 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4128 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4129 return false;
4130 return true;
4131}
4132
4133/// Return true if every element in Mask, beginning
4134/// from position Pos and ending in Pos+Size is undef or is zero.
4135static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4136 unsigned Size) {
4137 return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
4138}
4139
4140/// Return true if every element of a single input is referenced by the shuffle
4141/// mask. i.e. it just permutes them all.
4143 unsigned NumElts = Mask.size();
4144 APInt DemandedElts = APInt::getZero(NumElts);
4145 for (int M : Mask)
4146 if (isInRange(M, 0, NumElts))
4147 DemandedElts.setBit(M);
4148 return DemandedElts.isAllOnes();
4149}
4150
4151/// Helper function to test whether a shuffle mask could be
4152/// simplified by widening the elements being shuffled.
4153///
4154/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4155/// leaves it in an unspecified state.
4156///
4157/// NOTE: This must handle normal vector shuffle masks and *target* vector
4158/// shuffle masks. The latter have the special property of a '-2' representing
4159/// a zero-ed lane of a vector.
4161 SmallVectorImpl<int> &WidenedMask) {
4162 WidenedMask.assign(Mask.size() / 2, 0);
4163 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4164 int M0 = Mask[i];
4165 int M1 = Mask[i + 1];
4166
4167 // If both elements are undef, its trivial.
4168 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4169 WidenedMask[i / 2] = SM_SentinelUndef;
4170 continue;
4171 }
4172
4173 // Check for an undef mask and a mask value properly aligned to fit with
4174 // a pair of values. If we find such a case, use the non-undef mask's value.
4175 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4176 WidenedMask[i / 2] = M1 / 2;
4177 continue;
4178 }
4179 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4180 WidenedMask[i / 2] = M0 / 2;
4181 continue;
4182 }
4183
4184 // When zeroing, we need to spread the zeroing across both lanes to widen.
4185 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4186 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4188 WidenedMask[i / 2] = SM_SentinelZero;
4189 continue;
4190 }
4191 return false;
4192 }
4193
4194 // Finally check if the two mask values are adjacent and aligned with
4195 // a pair.
4196 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4197 WidenedMask[i / 2] = M0 / 2;
4198 continue;
4199 }
4200
4201 // Otherwise we can't safely widen the elements used in this shuffle.
4202 return false;
4203 }
4204 assert(WidenedMask.size() == Mask.size() / 2 &&
4205 "Incorrect size of mask after widening the elements!");
4206
4207 return true;
4208}
4209
4211 const APInt &Zeroable,
4212 bool V2IsZero,
4213 SmallVectorImpl<int> &WidenedMask) {
4214 // Create an alternative mask with info about zeroable elements.
4215 // Here we do not set undef elements as zeroable.
4216 SmallVector<int, 64> ZeroableMask(Mask);
4217 if (V2IsZero) {
4218 assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
4219 for (int i = 0, Size = Mask.size(); i != Size; ++i)
4220 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
4221 ZeroableMask[i] = SM_SentinelZero;
4222 }
4223 return canWidenShuffleElements(ZeroableMask, WidenedMask);
4224}
4225
4227 SmallVector<int, 32> WidenedMask;
4228 return canWidenShuffleElements(Mask, WidenedMask);
4229}
4230
4231// Attempt to narrow/widen shuffle mask until it matches the target number of
4232// elements.
4233static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
4234 SmallVectorImpl<int> &ScaledMask) {
4235 unsigned NumSrcElts = Mask.size();
4236 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
4237 "Illegal shuffle scale factor");
4238
4239 // Narrowing is guaranteed to work.
4240 if (NumDstElts >= NumSrcElts) {
4241 int Scale = NumDstElts / NumSrcElts;
4242 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
4243 return true;
4244 }
4245
4246 // We have to repeat the widening until we reach the target size, but we can
4247 // split out the first widening as it sets up ScaledMask for us.
4248 if (canWidenShuffleElements(Mask, ScaledMask)) {
4249 while (ScaledMask.size() > NumDstElts) {
4250 SmallVector<int, 16> WidenedMask;
4251 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
4252 return false;
4253 ScaledMask = std::move(WidenedMask);
4254 }
4255 return true;
4256 }
4257
4258 return false;
4259}
4260
4261static bool canScaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts) {
4262 SmallVector<int, 32> ScaledMask;
4263 return scaleShuffleElements(Mask, NumDstElts, ScaledMask);
4264}
4265
4266// Helper to grow the shuffle mask for a larger value type.
4267// NOTE: This is different to scaleShuffleElements which is a same size type.
4268static void growShuffleMask(ArrayRef<int> SrcMask,
4269 SmallVectorImpl<int> &DstMask,
4270 unsigned SrcSizeInBits, unsigned DstSizeInBits) {
4271 assert(DstMask.empty() && "Expected an empty shuffle mas");
4272 assert((DstSizeInBits % SrcSizeInBits) == 0 && "Illegal shuffle scale");
4273 unsigned Scale = DstSizeInBits / SrcSizeInBits;
4274 unsigned NumSrcElts = SrcMask.size();
4275 DstMask.assign(SrcMask.begin(), SrcMask.end());
4276 for (int &M : DstMask) {
4277 if (M < 0)
4278 continue;
4279 M = (M % NumSrcElts) + ((M / NumSrcElts) * Scale * NumSrcElts);
4280 }
4281 DstMask.append((Scale - 1) * NumSrcElts, SM_SentinelUndef);
4282}
4283
4284/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4286 return isNullConstant(Elt) || isNullFPConstant(Elt);
4287}
4288
4289// Build a vector of constants.
4290// Use an UNDEF node if MaskElt == -1.
4291// Split 64-bit constants in the 32-bit mode.
4293 const SDLoc &dl, bool IsMask = false) {
4294
4296 bool Split = false;
4297
4298 MVT ConstVecVT = VT;
4299 unsigned NumElts = VT.getVectorNumElements();
4300 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4301 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4302 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4303 Split = true;
4304 }
4305
4306 MVT EltVT = ConstVecVT.getVectorElementType();
4307 for (unsigned i = 0; i < NumElts; ++i) {
4308 bool IsUndef = Values[i] < 0 && IsMask;
4309 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4310 DAG.getConstant(Values[i], dl, EltVT);
4311 Ops.push_back(OpNode);
4312 if (Split)
4313 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4314 DAG.getConstant(0, dl, EltVT));
4315 }
4316 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4317 if (Split)
4318 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4319 return ConstsNode;
4320}
4321
4322static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
4323 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4324 assert(Bits.size() == Undefs.getBitWidth() &&
4325 "Unequal constant and undef arrays");
4327 bool Split = false;
4328
4329 MVT ConstVecVT = VT;
4330 unsigned NumElts = VT.getVectorNumElements();
4331 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4332 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4333 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4334 Split = true;
4335 }
4336
4337 MVT EltVT = ConstVecVT.getVectorElementType();
4338 MVT EltIntVT = EltVT.changeTypeToInteger();
4339 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
4340 if (Undefs[i]) {
4341 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
4342 continue;
4343 }
4344 const APInt &V = Bits[i];
4345 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
4346 if (Split) {
4347 Ops.push_back(DAG.getConstant(V.extractBits(32, 0), dl, EltVT));
4348 Ops.push_back(DAG.getConstant(V.extractBits(32, 32), dl, EltVT));
4349 } else {
4350 Ops.push_back(DAG.getBitcast(EltVT, DAG.getConstant(V, dl, EltIntVT)));
4351 }
4352 }
4353
4354 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4355 return DAG.getBitcast(VT, ConstsNode);
4356}
4357
4359 SelectionDAG &DAG, const SDLoc &dl) {
4360 APInt Undefs = APInt::getZero(Bits.size());
4361 return getConstVector(Bits, Undefs, VT, DAG, dl);
4362}
4363
4364/// Returns a vector of specified type with all zero elements.
4366 SelectionDAG &DAG, const SDLoc &dl) {
4367 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
4368 VT.getVectorElementType() == MVT::i1) &&
4369 "Unexpected vector type");
4370
4371 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4372 // type. This ensures they get CSE'd. But if the integer type is not
4373 // available, use a floating-point +0.0 instead.
4374 SDValue Vec;
4376 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4377 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4378 } else if (VT.isFloatingPoint() &&
4379 TLI.isTypeLegal(VT.getVectorElementType())) {
4380 Vec = DAG.getConstantFP(+0.0, dl, VT);
4381 } else if (VT.getVectorElementType() == MVT::i1) {
4382 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
4383 "Unexpected vector type");
4384 Vec = DAG.getConstant(0, dl, VT);
4385 } else {
4386 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4387 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4388 }
4389 return DAG.getBitcast(VT, Vec);
4390}
4391
4392// Helper to determine if the ops are all the extracted subvectors come from a
4393// single source. If we allow commute they don't have to be in order (Lo/Hi).
4394static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
4395 if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4396 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4397 LHS.getValueType() != RHS.getValueType() ||
4398 LHS.getOperand(0) != RHS.getOperand(0))
4399 return SDValue();
4400
4401 SDValue Src = LHS.getOperand(0);
4402 if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
4403 return SDValue();
4404
4405 unsigned NumElts = LHS.getValueType().getVectorNumElements();
4406 if ((LHS.getConstantOperandAPInt(1) == 0 &&
4407 RHS.getConstantOperandAPInt(1) == NumElts) ||
4408 (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
4409 LHS.getConstantOperandAPInt(1) == NumElts))
4410 return Src;
4411
4412 return SDValue();
4413}
4414
4415static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4416 const SDLoc &dl, unsigned vectorWidth) {
4417 EVT VT = Vec.getValueType();
4418 EVT ElVT = VT.getVectorElementType();
4419 unsigned ResultNumElts =
4420 (VT.getVectorNumElements() * vectorWidth) / VT.getSizeInBits();
4421 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, ResultNumElts);
4422
4423 assert(ResultVT.getSizeInBits() == vectorWidth &&
4424 "Illegal subvector extraction");
4425
4426 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4427 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4428 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4429
4430 // This is the index of the first element of the vectorWidth-bit chunk
4431 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4432 IdxVal &= ~(ElemsPerChunk - 1);
4433
4434 // If the input is a buildvector just emit a smaller one.
4435 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4436 return DAG.getBuildVector(ResultVT, dl,
4437 Vec->ops().slice(IdxVal, ElemsPerChunk));
4438
4439 // Check if we're extracting the upper undef of a widening pattern.
4440 if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
4441 Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
4442 isNullConstant(Vec.getOperand(2)))
4443 return DAG.getUNDEF(ResultVT);
4444
4445 return DAG.getExtractSubvector(dl, ResultVT, Vec, IdxVal);
4446}
4447
4448/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4449/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4450/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4451/// instructions or a simple subregister reference. Idx is an index in the
4452/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4453/// lowering EXTRACT_VECTOR_ELT operations easier.
4454static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4455 SelectionDAG &DAG, const SDLoc &dl) {
4457 Vec.getValueType().is512BitVector()) &&
4458 "Unexpected vector size!");
4459 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4460}
4461
4462/// Generate a DAG to grab 256-bits from a 512-bit vector.
4463static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4464 SelectionDAG &DAG, const SDLoc &dl) {
4465 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4466 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4467}
4468
4469static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4470 SelectionDAG &DAG, const SDLoc &dl,
4471 unsigned vectorWidth) {
4472 assert((vectorWidth == 128 || vectorWidth == 256) &&
4473 "Unsupported vector width");
4474 // Inserting UNDEF is Result
4475 if (Vec.isUndef())
4476 return Result;
4477
4478 // Insert the relevant vectorWidth bits.
4479 EVT VT = Vec.getValueType();
4480 unsigned ElemsPerChunk = vectorWidth / VT.getScalarSizeInBits();
4481 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4482
4483 // This is the index of the first element of the vectorWidth-bit chunk
4484 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4485 IdxVal &= ~(ElemsPerChunk - 1);
4486 return DAG.getInsertSubvector(dl, Result, Vec, IdxVal);
4487}
4488
4489/// Generate a DAG to put 128-bits into a vector > 128 bits. This
4490/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4491/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4492/// simple superregister reference. Idx is an index in the 128 bits
4493/// we want. It need not be aligned to a 128-bit boundary. That makes
4494/// lowering INSERT_VECTOR_ELT operations easier.
4495static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4496 SelectionDAG &DAG, const SDLoc &dl) {
4497 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4498 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4499}
4500
4501/// Widen a vector to a larger size with the same scalar type, with the new
4502/// elements either zero or undef.
4503static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
4504 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4505 const SDLoc &dl) {
4506 EVT VecVT = Vec.getValueType();
4508 VecVT.getScalarType() == VT.getScalarType() &&
4509 "Unsupported vector widening type");
4510 // If the upper 128-bits of a build vector are already undef/zero, then try to
4511 // widen from the lower 128-bits.
4512 if (Vec.getOpcode() == ISD::BUILD_VECTOR && VecVT.is256BitVector()) {
4513 unsigned NumSrcElts = VecVT.getVectorNumElements();
4514 ArrayRef<SDUse> Hi = Vec->ops().drop_front(NumSrcElts / 2);
4515 if (all_of(Hi, [&](SDValue V) {
4516 return V.isUndef() || (ZeroNewElements && X86::isZeroNode(V));
4517 }))
4518 Vec = extract128BitVector(Vec, 0, DAG, dl);
4519 }
4520 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
4521 : DAG.getUNDEF(VT);
4522 return DAG.getInsertSubvector(dl, Res, Vec, 0);
4523}
4524
4525/// Widen a vector to a larger size with the same scalar type, with the new
4526/// elements either zero or undef.
4527static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
4528 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4529 const SDLoc &dl, unsigned WideSizeInBits) {
4530 assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
4531 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
4532 "Unsupported vector widening type");
4533 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
4534 MVT SVT = Vec.getSimpleValueType().getScalarType();
4535 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
4536 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4537}
4538
4539/// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
4540/// and bitcast with integer types.
4542 assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
4543 unsigned NumElts = VT.getVectorNumElements();
4544 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
4545 return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4546 return VT;
4547}
4548
4549/// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
4550/// bitcast with integer types.
4551static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
4552 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4553 const SDLoc &dl) {
4555 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4556}
4557
4558// Helper function to collect subvector ops that are concatenated together,
4559// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
4560// The subvectors in Ops are guaranteed to be the same type.
4562 SelectionDAG &DAG) {
4563 assert(Ops.empty() && "Expected an empty ops vector");
4564
4565 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
4566 Ops.append(N->op_begin(), N->op_end());
4567 return true;
4568 }
4569
4570 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
4571 SDValue Src = N->getOperand(0);
4572 SDValue Sub = N->getOperand(1);
4573 const APInt &Idx = N->getConstantOperandAPInt(2);
4574 EVT VT = Src.getValueType();
4575 EVT SubVT = Sub.getValueType();
4576
4577 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
4578 // insert_subvector(undef, x, lo)
4579 if (Idx == 0 && Src.isUndef()) {
4580 Ops.push_back(Sub);
4581 Ops.push_back(DAG.getUNDEF(SubVT));
4582 return true;
4583 }
4584 if (Idx == (VT.getVectorNumElements() / 2)) {
4585 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
4586 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
4587 Src.getOperand(1).getValueType() == SubVT &&
4588 isNullConstant(Src.getOperand(2))) {
4589 // Attempt to recurse into inner (matching) concats.
4590 SDValue Lo = Src.getOperand(1);
4591 SDValue Hi = Sub;
4592 SmallVector<SDValue, 2> LoOps, HiOps;
4593 if (collectConcatOps(Lo.getNode(), LoOps, DAG) &&
4594 collectConcatOps(Hi.getNode(), HiOps, DAG) &&
4595 LoOps.size() == HiOps.size()) {
4596 Ops.append(LoOps);
4597 Ops.append(HiOps);
4598 return true;
4599 }
4600 Ops.push_back(Lo);
4601 Ops.push_back(Hi);
4602 return true;
4603 }
4604 // insert_subvector(x, extract_subvector(x, lo), hi)
4605 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4606 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
4607 Ops.append(2, Sub);
4608 return true;
4609 }
4610 // insert_subvector(undef, x, hi)
4611 if (Src.isUndef()) {
4612 Ops.push_back(DAG.getUNDEF(SubVT));
4613 Ops.push_back(Sub);
4614 return true;
4615 }
4616 }
4617 }
4618 }
4619
4620 if (N->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4621 EVT VT = N->getValueType(0);
4622 SDValue Src = N->getOperand(0);
4623 uint64_t Idx = N->getConstantOperandVal(1);
4624
4625 // Collect all the subvectors from the source vector and slice off the
4626 // extraction.
4628 if (collectConcatOps(Src.getNode(), SrcOps, DAG) &&
4629 VT.getSizeInBits() > SrcOps[0].getValueSizeInBits() &&
4630 (VT.getSizeInBits() % SrcOps[0].getValueSizeInBits()) == 0 &&
4631 (Idx % SrcOps[0].getValueType().getVectorNumElements()) == 0) {
4632 unsigned SubIdx = Idx / SrcOps[0].getValueType().getVectorNumElements();
4633 unsigned NumSubs = VT.getSizeInBits() / SrcOps[0].getValueSizeInBits();
4634 Ops.append(SrcOps.begin() + SubIdx, SrcOps.begin() + SubIdx + NumSubs);
4635 return true;
4636 }
4637 }
4638
4639 assert(Ops.empty() && "Expected an empty ops vector");
4640 return false;
4641}
4642
4643// Helper to check if \p V can be split into subvectors and the upper subvectors
4644// are all undef. In which case return the lower subvector.
4646 SelectionDAG &DAG) {
4647 SmallVector<SDValue> SubOps;
4648 if (!collectConcatOps(V.getNode(), SubOps, DAG))
4649 return SDValue();
4650
4651 unsigned NumSubOps = SubOps.size();
4652 unsigned HalfNumSubOps = NumSubOps / 2;
4653 assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
4654
4655 ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
4656 if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
4657 return SDValue();
4658
4659 EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
4660 ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
4661 return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
4662}
4663
4664// Helper to check if we can access all the constituent subvectors without any
4665// extract ops.
4668 return collectConcatOps(V.getNode(), Ops, DAG);
4669}
4670
4671static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4672 const SDLoc &dl) {
4673 EVT VT = Op.getValueType();
4674 unsigned NumElems = VT.getVectorNumElements();
4675 unsigned SizeInBits = VT.getSizeInBits();
4676 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4677 "Can't split odd sized vector");
4678
4680 if (collectConcatOps(Op.getNode(), SubOps, DAG)) {
4681 assert((SubOps.size() % 2) == 0 && "Can't split odd sized vector concat");
4682 unsigned HalfOps = SubOps.size() / 2;
4683 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
4684 SmallVector<SDValue, 2> LoOps(SubOps.begin(), SubOps.begin() + HalfOps);
4685 SmallVector<SDValue, 2> HiOps(SubOps.begin() + HalfOps, SubOps.end());
4686 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, LoOps);
4687 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, HiOps);
4688 return std::make_pair(Lo, Hi);
4689 }
4690
4691 // If this is a splat value (with no-undefs) then use the lower subvector,
4692 // which should be a free extraction.
4693 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4694 if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4695 return std::make_pair(Lo, Lo);
4696
4697 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4698 return std::make_pair(Lo, Hi);
4699}
4700
4701/// Break an operation into 2 half sized ops and then concatenate the results.
4703 unsigned NumOps = Op.getNumOperands();
4704 EVT VT = Op.getValueType();
4705
4706 // We've already folded to a BUILD_VECTOR, just return the original.
4707 if (Op.getOpcode() == ISD::BUILD_VECTOR)
4708 return Op;
4709
4710 // Extract the LHS Lo/Hi vectors
4713 for (unsigned I = 0; I != NumOps; ++I) {
4714 SDValue SrcOp = Op.getOperand(I);
4715 if (!SrcOp.getValueType().isVector()) {
4716 LoOps[I] = HiOps[I] = SrcOp;
4717 continue;
4718 }
4719 std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4720 }
4721
4722 EVT LoVT, HiVT;
4723 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4724 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4725 DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4726 DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4727}
4728
4729/// Break an unary integer operation into 2 half sized ops and then
4730/// concatenate the result back.
4732 const SDLoc &dl) {
4733 // Make sure we only try to split 256/512-bit types to avoid creating
4734 // narrow vectors.
4735 [[maybe_unused]] EVT VT = Op.getValueType();
4736 assert((Op.getOperand(0).getValueType().is256BitVector() ||
4737 Op.getOperand(0).getValueType().is512BitVector()) &&
4738 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4739 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4740 VT.getVectorNumElements() &&
4741 "Unexpected VTs!");
4742 return splitVectorOp(Op, DAG, dl);
4743}
4744
4745/// Break a binary integer operation into 2 half sized ops and then
4746/// concatenate the result back.
4748 const SDLoc &dl) {
4749 // Assert that all the types match.
4750 [[maybe_unused]] EVT VT = Op.getValueType();
4751 assert(Op.getOperand(0).getValueType() == VT &&
4752 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4753 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4754 return splitVectorOp(Op, DAG, dl);
4755}
4756
4757// Helper for splitting operands of an operation to legal target size and
4758// apply a function on each part.
4759// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4760// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4761// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4762// The argument Builder is a function that will be applied on each split part:
4763// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4764template <typename F>
4766 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4767 F Builder, bool CheckBWI = true,
4768 bool AllowAVX512 = true) {
4769 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4770 unsigned NumSubs = 1;
4771 if (AllowAVX512 && ((CheckBWI && Subtarget.useBWIRegs()) ||
4772 (!CheckBWI && Subtarget.useAVX512Regs()))) {
4773 if (VT.getSizeInBits() > 512) {
4774 NumSubs = VT.getSizeInBits() / 512;
4775 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4776 }
4777 } else if (Subtarget.hasAVX2()) {
4778 if (VT.getSizeInBits() > 256) {
4779 NumSubs = VT.getSizeInBits() / 256;
4780 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4781 }
4782 } else {
4783 if (VT.getSizeInBits() > 128) {
4784 NumSubs = VT.getSizeInBits() / 128;
4785 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4786 }
4787 }
4788
4789 if (NumSubs == 1)
4790 return Builder(DAG, DL, Ops);
4791
4793 for (unsigned i = 0; i != NumSubs; ++i) {
4795 for (SDValue Op : Ops) {
4796 EVT OpVT = Op.getValueType();
4797 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4798 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4799 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4800 }
4801 Subs.push_back(Builder(DAG, DL, SubOps));
4802 }
4803 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4804}
4805
4806// Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4807// targets.
4808static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4810 const X86Subtarget &Subtarget) {
4811 assert(Subtarget.hasAVX512() && "AVX512 target expected");
4812 MVT SVT = VT.getScalarType();
4813
4814 // If we have a 32/64 splatted constant, splat it to DstTy to
4815 // encourage a foldable broadcast'd operand.
4816 auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4817 unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4818 // AVX512 broadcasts 32/64-bit operands.
4819 // TODO: Support float once getAVX512Node is used by fp-ops.
4820 if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4822 return SDValue();
4823 // If we're not widening, don't bother if we're not bitcasting.
4824 if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4825 return SDValue();
4827 APInt SplatValue, SplatUndef;
4828 unsigned SplatBitSize;
4829 bool HasAnyUndefs;
4830 if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4831 HasAnyUndefs, OpEltSizeInBits) &&
4832 !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4833 return DAG.getConstant(SplatValue, DL, DstVT);
4834 }
4835 return SDValue();
4836 };
4837
4838 bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4839
4840 MVT DstVT = VT;
4841 if (Widen)
4842 DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4843
4844 // Canonicalize src operands.
4845 SmallVector<SDValue> SrcOps(Ops);
4846 for (SDValue &Op : SrcOps) {
4847 MVT OpVT = Op.getSimpleValueType();
4848 // Just pass through scalar operands.
4849 if (!OpVT.isVector())
4850 continue;
4851 assert(OpVT == VT && "Vector type mismatch");
4852
4853 if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4854 Op = BroadcastOp;
4855 continue;
4856 }
4857
4858 // Just widen the subvector by inserting into an undef wide vector.
4859 if (Widen)
4860 Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4861 }
4862
4863 SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4864
4865 // Perform the 512-bit op then extract the bottom subvector.
4866 if (Widen)
4867 Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4868 return Res;
4869}
4870
4871/// Insert i1-subvector to i1-vector.
4873 const X86Subtarget &Subtarget) {
4874
4875 SDLoc dl(Op);
4876 SDValue Vec = Op.getOperand(0);
4877 SDValue SubVec = Op.getOperand(1);
4878 SDValue Idx = Op.getOperand(2);
4879 unsigned IdxVal = Op.getConstantOperandVal(2);
4880
4881 // Inserting undef is a nop. We can just return the original vector.
4882 if (SubVec.isUndef())
4883 return Vec;
4884
4885 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4886 return Op;
4887
4888 MVT OpVT = Op.getSimpleValueType();
4889 unsigned NumElems = OpVT.getVectorNumElements();
4890 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, dl);
4891
4892 // Extend to natively supported kshift.
4893 MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4894
4895 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4896 // if necessary.
4897 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4898 // May need to promote to a legal type.
4899 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4900 DAG.getConstant(0, dl, WideOpVT),
4901 SubVec, Idx);
4902 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4903 }
4904
4905 MVT SubVecVT = SubVec.getSimpleValueType();
4906 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4907 assert(IdxVal + SubVecNumElems <= NumElems &&
4908 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4909 "Unexpected index value in INSERT_SUBVECTOR");
4910
4911 SDValue Undef = DAG.getUNDEF(WideOpVT);
4912
4913 if (IdxVal == 0) {
4914 // Zero lower bits of the Vec
4915 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4916 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4917 ZeroIdx);
4918 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4919 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4920 // Merge them together, SubVec should be zero extended.
4921 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4922 DAG.getConstant(0, dl, WideOpVT),
4923 SubVec, ZeroIdx);
4924 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4925 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4926 }
4927
4928 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4929 Undef, SubVec, ZeroIdx);
4930
4931 if (Vec.isUndef()) {
4932 assert(IdxVal != 0 && "Unexpected index");
4933 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4934 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4935 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4936 }
4937
4939 assert(IdxVal != 0 && "Unexpected index");
4940 // If upper elements of Vec are known undef, then just shift into place.
4941 if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4942 [](SDValue V) { return V.isUndef(); })) {
4943 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4944 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4945 } else {
4946 NumElems = WideOpVT.getVectorNumElements();
4947 unsigned ShiftLeft = NumElems - SubVecNumElems;
4948 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4949 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4950 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4951 if (ShiftRight != 0)
4952 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4953 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4954 }
4955 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4956 }
4957
4958 // Simple case when we put subvector in the upper part
4959 if (IdxVal + SubVecNumElems == NumElems) {
4960 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4961 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4962 if (SubVecNumElems * 2 == NumElems) {
4963 // Special case, use legal zero extending insert_subvector. This allows
4964 // isel to optimize when bits are known zero.
4965 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4966 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4967 DAG.getConstant(0, dl, WideOpVT),
4968 Vec, ZeroIdx);
4969 } else {
4970 // Otherwise use explicit shifts to zero the bits.
4971 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4972 Undef, Vec, ZeroIdx);
4973 NumElems = WideOpVT.getVectorNumElements();
4974 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4975 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4976 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4977 }
4978 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4979 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4980 }
4981
4982 // Inserting into the middle is more complicated.
4983
4984 NumElems = WideOpVT.getVectorNumElements();
4985
4986 // Widen the vector if needed.
4987 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4988
4989 unsigned ShiftLeft = NumElems - SubVecNumElems;
4990 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4991
4992 // Do an optimization for the most frequently used types.
4993 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4994 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4995 Mask0.flipAllBits();
4996 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4997 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4998 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4999 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5000 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5001 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5002 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5003 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5004
5005 // Reduce to original width if needed.
5006 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5007 }
5008
5009 // Clear the upper bits of the subvector and move it to its insert position.
5010 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5011 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5012 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5013 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5014
5015 // Isolate the bits below the insertion point.
5016 unsigned LowShift = NumElems - IdxVal;
5017 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
5018 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5019 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
5020 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5021
5022 // Isolate the bits after the last inserted bit.
5023 unsigned HighShift = IdxVal + SubVecNumElems;
5024 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5025 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5026 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
5027 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5028
5029 // Now OR all 3 pieces together.
5030 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
5031 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
5032
5033 // Reduce to original width if needed.
5034 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5035}
5036
5038 const SDLoc &dl) {
5039 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
5040 EVT SubVT = V1.getValueType();
5041 EVT SubSVT = SubVT.getScalarType();
5042 unsigned SubNumElts = SubVT.getVectorNumElements();
5043 unsigned SubVecWidth = SubVT.getSizeInBits();
5044 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
5045 SDValue V = insertSubVector(DAG.getPOISON(VT), V1, 0, DAG, dl, SubVecWidth);
5046 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVecWidth);
5047}
5048
5049/// Returns a vector of specified type with all bits set.
5050/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5051/// Then bitcast to their original type, ensuring they get CSE'd.
5052static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5053 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5054 "Expected a 128/256/512-bit vector type");
5055 unsigned NumElts = VT.getSizeInBits() / 32;
5056 SDValue Vec = DAG.getAllOnesConstant(dl, MVT::getVectorVT(MVT::i32, NumElts));
5057 return DAG.getBitcast(VT, Vec);
5058}
5059
5060// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
5061static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
5062 switch (Opc) {
5063 case ISD::SHL:
5064 case X86ISD::VSHL:
5065 case X86ISD::VSHLI:
5066 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
5067 case ISD::SRL:
5068 case X86ISD::VSRL:
5069 case X86ISD::VSRLI:
5070 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
5071 case ISD::SRA:
5072 case X86ISD::VSRA:
5073 case X86ISD::VSRAI:
5074 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
5075 }
5076 llvm_unreachable("Unknown target vector shift node");
5077}
5078
5079/// Handle vector element shifts where the shift amount is a constant.
5080/// Takes immediate version of shift as input.
5081static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
5082 SDValue SrcOp, uint64_t ShiftAmt,
5083 SelectionDAG &DAG) {
5084 assert(
5085 (Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) &&
5086 "Unknown target vector shift-by-constant node");
5087
5088 // Bitcast the source vector to the output type, this is mainly necessary for
5089 // vXi8/vXi64 shifts.
5090 SrcOp = DAG.getBitcast(VT, SrcOp);
5091
5092 // Fold this packed shift into its first operand if ShiftAmt is 0.
5093 if (ShiftAmt == 0)
5094 return SrcOp;
5095
5096 // Check for ShiftAmt >= element width
5097 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5098 if (ShiftAmt >= EltSizeInBits) {
5099 if (Opc == X86ISD::VSRAI)
5100 ShiftAmt = EltSizeInBits - 1;
5101 else
5102 return DAG.getConstant(0, dl, VT);
5103 }
5104
5105 // Fold this packed vector shift into a build vector if SrcOp is a
5106 // vector of Constants or UNDEFs.
5108 unsigned ShiftOpc;
5109 switch (Opc) {
5110 default:
5111 llvm_unreachable("Unknown opcode!");
5112 case X86ISD::VSHLI:
5113 ShiftOpc = ISD::SHL;
5114 break;
5115 case X86ISD::VSRLI:
5116 ShiftOpc = ISD::SRL;
5117 break;
5118 case X86ISD::VSRAI:
5119 ShiftOpc = ISD::SRA;
5120 break;
5121 }
5122
5123 SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
5124 if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
5125 return C;
5126 }
5127
5128 return DAG.getNode(Opc, dl, VT, SrcOp,
5129 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
5130}
5131
5132/// Handle vector element shifts by a splat shift amount
5133static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
5134 SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
5135 const X86Subtarget &Subtarget,
5136 SelectionDAG &DAG) {
5137 MVT AmtVT = ShAmt.getSimpleValueType();
5138 assert(AmtVT.isVector() && "Vector shift type mismatch");
5139 assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
5140 "Illegal vector splat index");
5141
5142 // Move the splat element to the bottom element.
5143 if (ShAmtIdx != 0) {
5144 SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
5145 Mask[0] = ShAmtIdx;
5146 ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
5147 }
5148
5149 // Peek through any zext node if we can get back to a 128-bit source.
5150 if (AmtVT.getScalarSizeInBits() == 64 &&
5151 (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
5153 ShAmt.getOperand(0).getValueType().isSimple() &&
5154 ShAmt.getOperand(0).getValueType().is128BitVector()) {
5155 ShAmt = ShAmt.getOperand(0);
5156 AmtVT = ShAmt.getSimpleValueType();
5157 }
5158
5159 // See if we can mask off the upper elements using the existing source node.
5160 // The shift uses the entire lower 64-bits of the amount vector, so no need to
5161 // do this for vXi64 types.
5162 bool IsMasked = false;
5163 if (AmtVT.getScalarSizeInBits() < 64) {
5164 if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
5165 ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5166 // If the shift amount has come from a scalar, then zero-extend the scalar
5167 // before moving to the vector.
5168 ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
5169 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
5170 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
5171 AmtVT = MVT::v4i32;
5172 IsMasked = true;
5173 } else if (ShAmt.getOpcode() == ISD::AND) {
5174 // See if the shift amount is already masked (e.g. for rotation modulo),
5175 // then we can zero-extend it by setting all the other mask elements to
5176 // zero.
5177 SmallVector<SDValue> MaskElts(
5178 AmtVT.getVectorNumElements(),
5179 DAG.getConstant(0, dl, AmtVT.getScalarType()));
5180 MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
5181 SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
5182 if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
5183 {ShAmt.getOperand(1), Mask}))) {
5184 ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
5185 IsMasked = true;
5186 }
5187 }
5188 }
5189
5190 // Extract if the shift amount vector is larger than 128-bits.
5191 if (AmtVT.getSizeInBits() > 128) {
5192 ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
5193 AmtVT = ShAmt.getSimpleValueType();
5194 }
5195
5196 // Zero-extend bottom element to v2i64 vector type, either by extension or
5197 // shuffle masking.
5198 if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
5199 if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
5200 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
5201 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
5202 } else if (Subtarget.hasSSE41()) {
5203 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
5204 MVT::v2i64, ShAmt);
5205 } else {
5206 SDValue ByteShift = DAG.getTargetConstant(
5207 (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
5208 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
5209 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5210 ByteShift);
5211 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5212 ByteShift);
5213 }
5214 }
5215
5216 // Change opcode to non-immediate version.
5218
5219 // The return type has to be a 128-bit type with the same element
5220 // type as the input type.
5221 MVT EltVT = VT.getVectorElementType();
5222 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
5223
5224 ShAmt = DAG.getBitcast(ShVT, ShAmt);
5225 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
5226}
5227
5228static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
5229 SDValue In, SelectionDAG &DAG) {
5230 EVT InVT = In.getValueType();
5231 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
5232
5233 // Canonicalize Opcode to general extension version.
5234 switch (Opcode) {
5235 case ISD::ANY_EXTEND:
5237 Opcode = ISD::ANY_EXTEND;
5238 break;
5239 case ISD::SIGN_EXTEND:
5241 Opcode = ISD::SIGN_EXTEND;
5242 break;
5243 case ISD::ZERO_EXTEND:
5245 Opcode = ISD::ZERO_EXTEND;
5246 break;
5247 default:
5248 llvm_unreachable("Unknown extension opcode");
5249 }
5250
5251 // For 256-bit vectors, we only need the lower (128-bit) input half.
5252 // For 512-bit vectors, we only need the lower input half or quarter.
5253 if (InVT.getSizeInBits() > 128) {
5254 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
5255 "Expected VTs to be the same size!");
5256 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5257 In = extractSubVector(In, 0, DAG, DL,
5258 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
5259 InVT = In.getValueType();
5260 }
5261
5262 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
5263 Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
5264
5265 return DAG.getNode(Opcode, DL, VT, In);
5266}
5267
5268// Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
5270 SDValue Mask, SelectionDAG &DAG) {
5271 LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
5272 RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
5273 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5274}
5275
5277 bool Lo, bool Unary) {
5278 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
5279 "Illegal vector type to unpack");
5280 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5281 int NumElts = VT.getVectorNumElements();
5282 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
5283 for (int i = 0; i < NumElts; ++i) {
5284 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
5285 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
5286 Pos += (Unary ? 0 : NumElts * (i % 2));
5287 Pos += (Lo ? 0 : NumEltsInLane / 2);
5288 Mask.push_back(Pos);
5289 }
5290}
5291
5292/// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
5293/// imposed by AVX and specific to the unary pattern. Example:
5294/// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
5295/// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
5297 bool Lo) {
5298 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5299 int NumElts = VT.getVectorNumElements();
5300 for (int i = 0; i < NumElts; ++i) {
5301 int Pos = i / 2;
5302 Pos += (Lo ? 0 : NumElts / 2);
5303 Mask.push_back(Pos);
5304 }
5305}
5306
5307// Attempt to constant fold, else just create a VECTOR_SHUFFLE.
5308static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
5309 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
5310 if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
5312 SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
5313 for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
5314 int M = Mask[I];
5315 if (M < 0)
5316 continue;
5317 SDValue V = (M < NumElts) ? V1 : V2;
5318 if (V.isUndef())
5319 continue;
5320 Ops[I] = V.getOperand(M % NumElts);
5321 }
5322 return DAG.getBuildVector(VT, dl, Ops);
5323 }
5324
5325 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5326}
5327
5328/// Returns a vector_shuffle node for an unpackl/h operation.
5329static SDValue getUnpack(SelectionDAG &DAG, const SDLoc &dl, EVT VT, SDValue V1,
5330 SDValue V2, bool UnpackHiHalf) {
5332 createUnpackShuffleMask(VT, Mask, /*Lo=*/!UnpackHiHalf, /*Unary=*/false);
5333 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5334}
5335
5336/// Returns a vector_shuffle node for an unpackl operation.
5337static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5338 SDValue V1, SDValue V2) {
5339 return getUnpack(DAG, dl, VT, V1, V2, /*UnpackHiHalf=*/false);
5340}
5341
5342/// Returns a vector_shuffle node for an unpackh operation.
5343static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5344 SDValue V1, SDValue V2) {
5345 return getUnpack(DAG, dl, VT, V1, V2, /*UnpackHiHalf=*/true);
5346}
5347
5348/// Returns a node that packs the LHS + RHS nodes together at half width.
5349/// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
5350/// TODO: Add subvector splitting if/when we have a need for it.
5352 const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
5353 bool PackHiHalf = false) {
5354 MVT OpVT = LHS.getSimpleValueType();
5355 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5356 bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
5357 assert(OpVT == RHS.getSimpleValueType() &&
5358 VT.getSizeInBits() == OpVT.getSizeInBits() &&
5359 (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
5360 "Unexpected PACK operand types");
5361 assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
5362 "Unexpected PACK result type");
5363
5364 // Rely on vector shuffles for vXi64 -> vXi32 packing.
5365 if (EltSizeInBits == 32) {
5366 SmallVector<int> PackMask;
5367 int Offset = PackHiHalf ? 1 : 0;
5368 int NumElts = VT.getVectorNumElements();
5369 for (int I = 0; I != NumElts; I += 4) {
5370 PackMask.push_back(I + Offset);
5371 PackMask.push_back(I + Offset + 2);
5372 PackMask.push_back(I + Offset + NumElts);
5373 PackMask.push_back(I + Offset + NumElts + 2);
5374 }
5375 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
5376 DAG.getBitcast(VT, RHS), PackMask);
5377 }
5378
5379 // See if we already have sufficient leading bits for PACKSS/PACKUS.
5380 if (!PackHiHalf) {
5381 if (UsePackUS &&
5382 DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
5383 DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
5384 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5385
5386 if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
5387 DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
5388 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5389 }
5390
5391 // Fallback to sign/zero extending the requested half and pack.
5392 SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
5393 if (UsePackUS) {
5394 if (PackHiHalf) {
5395 LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
5396 RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
5397 } else {
5398 SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
5399 LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
5400 RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
5401 };
5402 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5403 };
5404
5405 if (!PackHiHalf) {
5406 LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
5407 RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
5408 }
5409 LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
5410 RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
5411 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5412}
5413
5414/// Return a vector_shuffle of the specified vector of zero or undef vector.
5415/// This produces a shuffle where the low element of V2 is swizzled into the
5416/// zero/undef vector, landing at element Idx.
5417/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5419 bool IsZero,
5420 const X86Subtarget &Subtarget,
5421 SelectionDAG &DAG) {
5422 MVT VT = V2.getSimpleValueType();
5423 SDValue V1 = IsZero
5424 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5425 int NumElems = VT.getVectorNumElements();
5426 SmallVector<int, 16> MaskVec(NumElems);
5427 for (int i = 0; i != NumElems; ++i)
5428 // If this is the insertion idx, put the low elt of V2 here.
5429 MaskVec[i] = (i == Idx) ? NumElems : i;
5430 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5431}
5432
5434 if (Ptr.getOpcode() == X86ISD::Wrapper ||
5435 Ptr.getOpcode() == X86ISD::WrapperRIP)
5436 Ptr = Ptr.getOperand(0);
5437 return dyn_cast<ConstantPoolSDNode>(Ptr);
5438}
5439
5440// TODO: Add support for non-zero offsets.
5443 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5444 return nullptr;
5445 return CNode->getConstVal();
5446}
5447
5449 if (!Load || !ISD::isNormalLoad(Load))
5450 return nullptr;
5451 return getTargetConstantFromBasePtr(Load->getBasePtr());
5452}
5453
5458
5459const Constant *
5461 assert(LD && "Unexpected null LoadSDNode");
5462 return getTargetConstantFromNode(LD);
5463}
5464
5466 // Do not fold (vselect not(C), X, 0s) to (vselect C, Os, X)
5467 SDValue Cond = N->getOperand(0);
5468 SDValue RHS = N->getOperand(2);
5469 EVT CondVT = Cond.getValueType();
5470 return N->getOpcode() == ISD::VSELECT && Subtarget.hasAVX512() &&
5471 CondVT.getVectorElementType() == MVT::i1 &&
5472 ISD::isBuildVectorAllZeros(RHS.getNode());
5473}
5474
5475// Extract raw constant bits from constant pools.
5476static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5477 APInt &UndefElts,
5478 SmallVectorImpl<APInt> &EltBits,
5479 bool AllowWholeUndefs = true,
5480 bool AllowPartialUndefs = false) {
5481 assert(EltBits.empty() && "Expected an empty EltBits vector");
5482
5484
5485 EVT VT = Op.getValueType();
5486 unsigned SizeInBits = VT.getSizeInBits();
5487 unsigned NumElts = SizeInBits / EltSizeInBits;
5488
5489 // Can't split constant.
5490 if ((SizeInBits % EltSizeInBits) != 0)
5491 return false;
5492
5493 // Bitcast a source array of element bits to the target size.
5494 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5495 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5496 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5497 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
5498 "Constant bit sizes don't match");
5499
5500 // Don't split if we don't allow undef bits.
5501 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5502 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5503 return false;
5504
5505 // If we're already the right size, don't bother bitcasting.
5506 if (NumSrcElts == NumElts) {
5507 UndefElts = UndefSrcElts;
5508 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5509 return true;
5510 }
5511
5512 // Extract all the undef/constant element data and pack into single bitsets.
5513 APInt UndefBits(SizeInBits, 0);
5514 APInt MaskBits(SizeInBits, 0);
5515
5516 for (unsigned i = 0; i != NumSrcElts; ++i) {
5517 unsigned BitOffset = i * SrcEltSizeInBits;
5518 if (UndefSrcElts[i])
5519 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5520 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5521 }
5522
5523 // Split the undef/constant single bitset data into the target elements.
5524 UndefElts = APInt(NumElts, 0);
5525 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5526
5527 for (unsigned i = 0; i != NumElts; ++i) {
5528 unsigned BitOffset = i * EltSizeInBits;
5529 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5530
5531 // Only treat an element as UNDEF if all bits are UNDEF.
5532 if (UndefEltBits.isAllOnes()) {
5533 if (!AllowWholeUndefs)
5534 return false;
5535 UndefElts.setBit(i);
5536 continue;
5537 }
5538
5539 // If only some bits are UNDEF then treat them as zero (or bail if not
5540 // supported).
5541 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5542 return false;
5543
5544 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
5545 }
5546 return true;
5547 };
5548
5549 // Collect constant bits and insert into mask/undef bit masks.
5550 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5551 unsigned UndefBitIndex) {
5552 if (!Cst)
5553 return false;
5554 if (isa<UndefValue>(Cst)) {
5555 Undefs.setBit(UndefBitIndex);
5556 return true;
5557 }
5558 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5559 Mask = APInt::getSplat(CInt->getType()->getPrimitiveSizeInBits(),
5560 CInt->getValue());
5561 return true;
5562 }
5563 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5564 Mask = APInt::getSplat(CFP->getType()->getPrimitiveSizeInBits(),
5565 CFP->getValueAPF().bitcastToAPInt());
5566 return true;
5567 }
5568 if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
5569 Type *Ty = CDS->getType();
5570 if (Ty->isVectorTy()) {
5571 Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
5572 Type *EltTy = CDS->getElementType();
5573 bool IsInteger = EltTy->isIntegerTy();
5574 bool IsFP =
5575 EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
5576 if (!IsInteger && !IsFP)
5577 return false;
5578 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
5579 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
5580 if (IsInteger)
5581 Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
5582 else
5583 Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
5584 I * EltBits);
5585 return true;
5586 }
5587 }
5588 return false;
5589 };
5590
5591 // Handle UNDEFs.
5592 if (Op.isUndef()) {
5593 APInt UndefSrcElts = APInt::getAllOnes(NumElts);
5594 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5595 return CastBitData(UndefSrcElts, SrcEltBits);
5596 }
5597
5598 // Extract scalar constant bits.
5599 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5600 APInt UndefSrcElts = APInt::getZero(1);
5601 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5602 return CastBitData(UndefSrcElts, SrcEltBits);
5603 }
5604 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5605 APInt UndefSrcElts = APInt::getZero(1);
5606 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5607 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5608 return CastBitData(UndefSrcElts, SrcEltBits);
5609 }
5610
5611 // Extract constant bits from build vector.
5612 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5613 BitVector Undefs;
5614 SmallVector<APInt> SrcEltBits;
5615 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5616 if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
5617 APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
5618 for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
5619 if (Undefs[I])
5620 UndefSrcElts.setBit(I);
5621 return CastBitData(UndefSrcElts, SrcEltBits);
5622 }
5623 }
5624
5625 // Extract constant bits from constant pool vector.
5626 if (auto *Cst = getTargetConstantFromNode(Op)) {
5627 Type *CstTy = Cst->getType();
5628 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5629 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5630 return false;
5631
5632 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5633 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5634 if ((SizeInBits % SrcEltSizeInBits) != 0)
5635 return false;
5636
5637 APInt UndefSrcElts(NumSrcElts, 0);
5638 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5639 for (unsigned i = 0; i != NumSrcElts; ++i)
5640 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5641 UndefSrcElts, i))
5642 return false;
5643
5644 return CastBitData(UndefSrcElts, SrcEltBits);
5645 }
5646
5647 // Extract constant bits from a broadcasted constant pool scalar.
5648 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
5649 EltSizeInBits <= VT.getScalarSizeInBits()) {
5650 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5651 if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
5652 return false;
5653
5654 SDValue Ptr = MemIntr->getBasePtr();
5655 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
5656 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5657 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5658
5659 APInt UndefSrcElts(NumSrcElts, 0);
5660 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5661 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
5662 if (UndefSrcElts[0])
5663 UndefSrcElts.setBits(0, NumSrcElts);
5664 if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
5665 SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
5666 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5667 return CastBitData(UndefSrcElts, SrcEltBits);
5668 }
5669 }
5670 }
5671
5672 // Extract constant bits from a subvector broadcast.
5673 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
5674 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5675 SDValue Ptr = MemIntr->getBasePtr();
5676 // The source constant may be larger than the subvector broadcast,
5677 // ensure we extract the correct subvector constants.
5678 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
5679 Type *CstTy = Cst->getType();
5680 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5681 unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
5682 if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
5683 (SizeInBits % SubVecSizeInBits) != 0)
5684 return false;
5685 unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
5686 unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
5687 unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
5688 APInt UndefSubElts(NumSubElts, 0);
5689 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
5690 APInt(CstEltSizeInBits, 0));
5691 for (unsigned i = 0; i != NumSubElts; ++i) {
5692 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
5693 UndefSubElts, i))
5694 return false;
5695 for (unsigned j = 1; j != NumSubVecs; ++j)
5696 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
5697 }
5698 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
5699 UndefSubElts);
5700 return CastBitData(UndefSubElts, SubEltBits);
5701 }
5702 }
5703
5704 // Extract a rematerialized scalar constant insertion.
5705 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5706 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5707 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5708 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5709 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5710
5711 APInt UndefSrcElts(NumSrcElts, 0);
5712 SmallVector<APInt, 64> SrcEltBits;
5713 const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
5714 SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
5715 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5716 return CastBitData(UndefSrcElts, SrcEltBits);
5717 }
5718
5719 // Insert constant bits from a base and sub vector sources.
5720 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
5721 // If bitcasts to larger elements we might lose track of undefs - don't
5722 // allow any to be safe.
5723 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5724 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
5725
5726 APInt UndefSrcElts, UndefSubElts;
5727 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
5728 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
5729 UndefSubElts, EltSubBits,
5730 AllowWholeUndefs && AllowUndefs,
5731 AllowPartialUndefs && AllowUndefs) &&
5732 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
5733 UndefSrcElts, EltSrcBits,
5734 AllowWholeUndefs && AllowUndefs,
5735 AllowPartialUndefs && AllowUndefs)) {
5736 unsigned BaseIdx = Op.getConstantOperandVal(2);
5737 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
5738 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
5739 EltSrcBits[BaseIdx + i] = EltSubBits[i];
5740 return CastBitData(UndefSrcElts, EltSrcBits);
5741 }
5742 }
5743
5744 // Extract constant bits from a subvector's source.
5745 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5746 getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits, UndefElts,
5747 EltBits, AllowWholeUndefs,
5748 AllowPartialUndefs)) {
5749 EVT SrcVT = Op.getOperand(0).getValueType();
5750 unsigned NumSrcElts = SrcVT.getSizeInBits() / EltSizeInBits;
5751 unsigned NumSubElts = VT.getSizeInBits() / EltSizeInBits;
5752 unsigned BaseOfs = Op.getConstantOperandVal(1) * VT.getScalarSizeInBits();
5753 unsigned BaseIdx = BaseOfs / EltSizeInBits;
5754 assert((SrcVT.getSizeInBits() % EltSizeInBits) == 0 &&
5755 (VT.getSizeInBits() % EltSizeInBits) == 0 &&
5756 (BaseOfs % EltSizeInBits) == 0 && "Bad subvector index");
5757
5758 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5759 if ((BaseIdx + NumSubElts) != NumSrcElts)
5760 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5761 if (BaseIdx != 0)
5762 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5763 return true;
5764 }
5765
5766 // Extract constant bits from shuffle node sources.
5767 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5768 // TODO - support shuffle through bitcasts.
5769 if (EltSizeInBits != VT.getScalarSizeInBits())
5770 return false;
5771
5772 ArrayRef<int> Mask = SVN->getMask();
5773 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5774 llvm::any_of(Mask, [](int M) { return M < 0; }))
5775 return false;
5776
5777 APInt UndefElts0, UndefElts1;
5778 SmallVector<APInt, 32> EltBits0, EltBits1;
5779 if (isAnyInRange(Mask, 0, NumElts) &&
5780 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5781 UndefElts0, EltBits0, AllowWholeUndefs,
5782 AllowPartialUndefs))
5783 return false;
5784 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5785 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5786 UndefElts1, EltBits1, AllowWholeUndefs,
5787 AllowPartialUndefs))
5788 return false;
5789
5790 UndefElts = APInt::getZero(NumElts);
5791 for (int i = 0; i != (int)NumElts; ++i) {
5792 int M = Mask[i];
5793 if (M < 0) {
5794 UndefElts.setBit(i);
5795 EltBits.push_back(APInt::getZero(EltSizeInBits));
5796 } else if (M < (int)NumElts) {
5797 if (UndefElts0[M])
5798 UndefElts.setBit(i);
5799 EltBits.push_back(EltBits0[M]);
5800 } else {
5801 if (UndefElts1[M - NumElts])
5802 UndefElts.setBit(i);
5803 EltBits.push_back(EltBits1[M - NumElts]);
5804 }
5805 }
5806 return true;
5807 }
5808
5809 return false;
5810}
5811
5812namespace llvm {
5813namespace X86 {
5814bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
5815 APInt UndefElts;
5816 SmallVector<APInt, 16> EltBits;
5818 Op, Op.getScalarValueSizeInBits(), UndefElts, EltBits,
5819 /*AllowWholeUndefs*/ true, AllowPartialUndefs)) {
5820 int SplatIndex = -1;
5821 for (int i = 0, e = EltBits.size(); i != e; ++i) {
5822 if (UndefElts[i])
5823 continue;
5824 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5825 SplatIndex = -1;
5826 break;
5827 }
5828 SplatIndex = i;
5829 }
5830 if (0 <= SplatIndex) {
5831 SplatVal = EltBits[SplatIndex];
5832 return true;
5833 }
5834 }
5835
5836 return false;
5837}
5838
5839int getRoundingModeX86(unsigned RM) {
5840 switch (static_cast<::llvm::RoundingMode>(RM)) {
5841 // clang-format off
5842 case ::llvm::RoundingMode::NearestTiesToEven: return X86::rmToNearest;
5843 case ::llvm::RoundingMode::TowardNegative: return X86::rmDownward;
5844 case ::llvm::RoundingMode::TowardPositive: return X86::rmUpward;
5845 case ::llvm::RoundingMode::TowardZero: return X86::rmTowardZero;
5846 default: return X86::rmInvalid;
5847 // clang-format on
5848 }
5849}
5850
5851} // namespace X86
5852} // namespace llvm
5853
5855 unsigned MaskEltSizeInBits,
5857 APInt &UndefElts) {
5858 // Extract the raw target constant bits.
5859 SmallVector<APInt, 64> EltBits;
5860 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5861 EltBits, /* AllowWholeUndefs */ true,
5862 /* AllowPartialUndefs */ false))
5863 return false;
5864
5865 // Insert the extracted elements into the mask.
5866 for (const APInt &Elt : EltBits)
5867 RawMask.push_back(Elt.getZExtValue());
5868
5869 return true;
5870}
5871
5872static bool isConstantPowerOf2(SDValue V, unsigned EltSizeInBIts,
5873 bool AllowUndefs) {
5874 APInt UndefElts;
5875 SmallVector<APInt, 64> EltBits;
5876 if (!getTargetConstantBitsFromNode(V, EltSizeInBIts, UndefElts, EltBits,
5877 /*AllowWholeUndefs*/ AllowUndefs,
5878 /*AllowPartialUndefs*/ false))
5879 return false;
5880
5881 bool IsPow2OrUndef = true;
5882 for (unsigned I = 0, E = EltBits.size(); I != E; ++I)
5883 IsPow2OrUndef &= UndefElts[I] || EltBits[I].isPowerOf2();
5884 return IsPow2OrUndef;
5885}
5886
5887// Helper to attempt to return a cheaper, bit-inverted version of \p V.
5889 // TODO: don't always ignore oneuse constraints.
5891 EVT VT = V.getValueType();
5892
5893 // Match not(xor X, -1) -> X.
5894 if (V.getOpcode() == ISD::XOR &&
5895 (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
5896 isAllOnesConstant(V.getOperand(1))))
5897 return V.getOperand(0);
5898
5899 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
5900 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5901 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5902 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5903 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5904 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
5905 V.getOperand(1));
5906 }
5907 }
5908
5909 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
5910 if (V.getOpcode() == X86ISD::PCMPGT &&
5911 !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
5912 !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
5913 V.getOperand(0).hasOneUse()) {
5914 APInt UndefElts;
5915 SmallVector<APInt> EltBits;
5916 if (getTargetConstantBitsFromNode(V.getOperand(0),
5917 V.getScalarValueSizeInBits(), UndefElts,
5918 EltBits) &&
5919 !ISD::isBuildVectorOfConstantSDNodes(V.getOperand(1).getNode())) {
5920 // Don't fold min_signed_value -> (min_signed_value - 1)
5921 bool MinSigned = false;
5922 for (APInt &Elt : EltBits) {
5923 MinSigned |= Elt.isMinSignedValue();
5924 Elt -= 1;
5925 }
5926 if (!MinSigned) {
5927 SDLoc DL(V);
5928 MVT VT = V.getSimpleValueType();
5929 return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5930 getConstVector(EltBits, UndefElts, VT, DAG, DL));
5931 }
5932 }
5933 }
5934
5935 // Match not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
5937 if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5938 for (SDValue &CatOp : CatOps) {
5939 SDValue NotCat = IsNOT(CatOp, DAG);
5940 if (!NotCat)
5941 return SDValue();
5942 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5943 }
5944 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), VT, CatOps);
5945 }
5946
5947 // Match not(or(not(X),not(Y))) -> and(X, Y).
5948 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
5949 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
5950 // TODO: Handle cases with single NOT operand -> ANDNP
5951 if (SDValue Op1 = IsNOT(V.getOperand(1), DAG))
5952 if (SDValue Op0 = IsNOT(V.getOperand(0), DAG))
5953 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
5954 DAG.getBitcast(VT, Op1));
5955 }
5956
5957 return SDValue();
5958}
5959
5960/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5961/// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5962/// Note: This ignores saturation, so inputs must be checked first.
5964 bool Unary, unsigned NumStages = 1) {
5965 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5966 unsigned NumElts = VT.getVectorNumElements();
5967 unsigned NumLanes = VT.getSizeInBits() / 128;
5968 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5969 unsigned Offset = Unary ? 0 : NumElts;
5970 unsigned Repetitions = 1u << (NumStages - 1);
5971 unsigned Increment = 1u << NumStages;
5972 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5973
5974 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5975 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5976 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5977 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5978 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5979 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5980 }
5981 }
5982}
5983
5984// Split the demanded elts of a PACKSS/PACKUS node between its operands.
5985static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5986 APInt &DemandedLHS, APInt &DemandedRHS) {
5987 int NumLanes = VT.getSizeInBits() / 128;
5988 int NumElts = DemandedElts.getBitWidth();
5989 int NumInnerElts = NumElts / 2;
5990 int NumEltsPerLane = NumElts / NumLanes;
5991 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5992
5993 DemandedLHS = APInt::getZero(NumInnerElts);
5994 DemandedRHS = APInt::getZero(NumInnerElts);
5995
5996 // Map DemandedElts to the packed operands.
5997 for (int Lane = 0; Lane != NumLanes; ++Lane) {
5998 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5999 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6000 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6001 if (DemandedElts[OuterIdx])
6002 DemandedLHS.setBit(InnerIdx);
6003 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6004 DemandedRHS.setBit(InnerIdx);
6005 }
6006 }
6007}
6008
6009// Split the demanded elts of a HADD/HSUB node between its operands.
6010static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6011 APInt &DemandedLHS, APInt &DemandedRHS) {
6013 DemandedLHS, DemandedRHS);
6014 DemandedLHS |= DemandedLHS << 1;
6015 DemandedRHS |= DemandedRHS << 1;
6016}
6017
6018/// Calculates the shuffle mask corresponding to the target-specific opcode.
6019/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6020/// operands in \p Ops, and returns true.
6021/// Sets \p IsUnary to true if only one source is used. Note that this will set
6022/// IsUnary for shuffles which use a single input multiple times, and in those
6023/// cases it will adjust the mask to only have indices within that single input.
6024/// It is an error to call this with non-empty Mask/Ops vectors.
6025static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6027 SmallVectorImpl<int> &Mask, bool &IsUnary) {
6028 if (!isTargetShuffle(N.getOpcode()))
6029 return false;
6030
6031 MVT VT = N.getSimpleValueType();
6032 unsigned NumElems = VT.getVectorNumElements();
6033 unsigned MaskEltSize = VT.getScalarSizeInBits();
6035 APInt RawUndefs;
6036 uint64_t ImmN;
6037
6038 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6039 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6040
6041 IsUnary = false;
6042 bool IsFakeUnary = false;
6043 switch (N.getOpcode()) {
6044 case X86ISD::BLENDI:
6045 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6046 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6047 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6048 DecodeBLENDMask(NumElems, ImmN, Mask);
6049 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6050 break;
6051 case X86ISD::SHUFP:
6052 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6053 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6054 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6055 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6056 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6057 break;
6058 case X86ISD::INSERTPS:
6059 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6060 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6061 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6062 DecodeINSERTPSMask(ImmN, Mask, /*SrcIsMem=*/false);
6063 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6064 break;
6065 case X86ISD::EXTRQI:
6066 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6067 if (isa<ConstantSDNode>(N.getOperand(1)) &&
6068 isa<ConstantSDNode>(N.getOperand(2))) {
6069 int BitLen = N.getConstantOperandVal(1);
6070 int BitIdx = N.getConstantOperandVal(2);
6071 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6072 IsUnary = true;
6073 }
6074 break;
6075 case X86ISD::INSERTQI:
6076 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6077 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6078 if (isa<ConstantSDNode>(N.getOperand(2)) &&
6079 isa<ConstantSDNode>(N.getOperand(3))) {
6080 int BitLen = N.getConstantOperandVal(2);
6081 int BitIdx = N.getConstantOperandVal(3);
6082 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6083 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6084 }
6085 break;
6086 case X86ISD::UNPCKH:
6087 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6088 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6089 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6090 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6091 break;
6092 case X86ISD::UNPCKL:
6093 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6094 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6095 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6096 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6097 break;
6098 case X86ISD::MOVHLPS:
6099 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6100 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6101 DecodeMOVHLPSMask(NumElems, Mask);
6102 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6103 break;
6104 case X86ISD::MOVLHPS:
6105 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6106 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6107 DecodeMOVLHPSMask(NumElems, Mask);
6108 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6109 break;
6110 case X86ISD::VALIGN:
6111 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
6112 "Only 32-bit and 64-bit elements are supported!");
6113 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6114 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6115 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6116 DecodeVALIGNMask(NumElems, ImmN, Mask);
6117 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6118 Ops.push_back(N.getOperand(1));
6119 Ops.push_back(N.getOperand(0));
6120 break;
6121 case X86ISD::PALIGNR:
6122 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6123 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6124 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6125 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6126 DecodePALIGNRMask(NumElems, ImmN, Mask);
6127 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6128 Ops.push_back(N.getOperand(1));
6129 Ops.push_back(N.getOperand(0));
6130 break;
6131 case X86ISD::VSHLDQ:
6132 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6133 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6134 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6135 DecodePSLLDQMask(NumElems, ImmN, Mask);
6136 IsUnary = true;
6137 break;
6138 case X86ISD::VSRLDQ:
6139 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6140 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6141 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6142 DecodePSRLDQMask(NumElems, ImmN, Mask);
6143 IsUnary = true;
6144 break;
6145 case X86ISD::PSHUFD:
6146 case X86ISD::VPERMILPI:
6147 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6148 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6149 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
6150 IsUnary = true;
6151 break;
6152 case X86ISD::PSHUFHW:
6153 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6154 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6155 DecodePSHUFHWMask(NumElems, ImmN, Mask);
6156 IsUnary = true;
6157 break;
6158 case X86ISD::PSHUFLW:
6159 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6160 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6161 DecodePSHUFLWMask(NumElems, ImmN, Mask);
6162 IsUnary = true;
6163 break;
6164 case X86ISD::VZEXT_MOVL:
6165 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6166 DecodeZeroMoveLowMask(NumElems, Mask);
6167 IsUnary = true;
6168 break;
6169 case X86ISD::VBROADCAST:
6170 // We only decode broadcasts of same-sized vectors, peeking through to
6171 // extracted subvectors is likely to cause hasOneUse issues with
6172 // SimplifyDemandedBits etc.
6173 if (N.getOperand(0).getValueType() == VT) {
6174 DecodeVectorBroadcast(NumElems, Mask);
6175 IsUnary = true;
6176 break;
6177 }
6178 return false;
6179 case X86ISD::VPERMILPV: {
6180 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6181 IsUnary = true;
6182 SDValue MaskNode = N.getOperand(1);
6183 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6184 RawUndefs)) {
6185 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6186 break;
6187 }
6188 return false;
6189 }
6190 case X86ISD::PSHUFB: {
6191 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6192 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6193 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6194 IsUnary = true;
6195 SDValue MaskNode = N.getOperand(1);
6196 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6197 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6198 break;
6199 }
6200 return false;
6201 }
6202 case X86ISD::VPERMI:
6203 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6204 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6205 DecodeVPERMMask(NumElems, ImmN, Mask);
6206 IsUnary = true;
6207 break;
6208 case X86ISD::MOVSS:
6209 case X86ISD::MOVSD:
6210 case X86ISD::MOVSH:
6211 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6212 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6213 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6214 break;
6215 case X86ISD::VPERM2X128:
6216 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6217 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6218 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6219 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
6220 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6221 break;
6222 case X86ISD::SHUF128:
6223 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6224 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6225 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6226 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
6227 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6228 break;
6229 case X86ISD::MOVSLDUP:
6230 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6231 DecodeMOVSLDUPMask(NumElems, Mask);
6232 IsUnary = true;
6233 break;
6234 case X86ISD::MOVSHDUP:
6235 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6236 DecodeMOVSHDUPMask(NumElems, Mask);
6237 IsUnary = true;
6238 break;
6239 case X86ISD::MOVDDUP:
6240 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6241 DecodeMOVDDUPMask(NumElems, Mask);
6242 IsUnary = true;
6243 break;
6244 case X86ISD::VPERMIL2: {
6245 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6246 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6247 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6248 SDValue MaskNode = N.getOperand(2);
6249 SDValue CtrlNode = N.getOperand(3);
6250 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6251 unsigned CtrlImm = CtrlOp->getZExtValue();
6252 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6253 RawUndefs)) {
6254 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6255 Mask);
6256 break;
6257 }
6258 }
6259 return false;
6260 }
6261 case X86ISD::VPPERM: {
6262 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6263 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6264 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6265 SDValue MaskNode = N.getOperand(2);
6266 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6267 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6268 break;
6269 }
6270 return false;
6271 }
6272 case X86ISD::VPERMV: {
6273 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6274 IsUnary = true;
6275 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6276 Ops.push_back(N.getOperand(1));
6277 SDValue MaskNode = N.getOperand(0);
6278 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6279 RawUndefs)) {
6280 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6281 break;
6282 }
6283 return false;
6284 }
6285 case X86ISD::VPERMV3: {
6286 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6287 assert(N.getOperand(2).getValueType() == VT && "Unexpected value type");
6288 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(2);
6289 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6290 Ops.push_back(N.getOperand(0));
6291 Ops.push_back(N.getOperand(2));
6292 SDValue MaskNode = N.getOperand(1);
6293 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6294 RawUndefs)) {
6295 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6296 break;
6297 }
6298 return false;
6299 }
6300 case X86ISD::COMPRESS: {
6301 SDValue CmpVec = N.getOperand(0);
6302 SDValue PassThru = N.getOperand(1);
6303 SDValue CmpMask = N.getOperand(2);
6304 APInt UndefElts;
6305 SmallVector<APInt> EltBits;
6306 if (!getTargetConstantBitsFromNode(CmpMask, 1, UndefElts, EltBits))
6307 return false;
6308 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6309 "Illegal compression mask");
6310 for (unsigned I = 0; I != NumElems; ++I) {
6311 if (!EltBits[I].isZero())
6312 Mask.push_back(I);
6313 }
6314 while (Mask.size() != NumElems) {
6315 Mask.push_back(NumElems + Mask.size());
6316 }
6317 Ops.push_back(CmpVec);
6318 Ops.push_back(PassThru);
6319 return true;
6320 }
6321 case X86ISD::EXPAND: {
6322 SDValue ExpVec = N.getOperand(0);
6323 SDValue PassThru = N.getOperand(1);
6324 SDValue ExpMask = N.getOperand(2);
6325 APInt UndefElts;
6326 SmallVector<APInt> EltBits;
6327 if (!getTargetConstantBitsFromNode(ExpMask, 1, UndefElts, EltBits))
6328 return false;
6329 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6330 "Illegal expansion mask");
6331 unsigned ExpIndex = 0;
6332 for (unsigned I = 0; I != NumElems; ++I) {
6333 if (EltBits[I].isZero())
6334 Mask.push_back(I + NumElems);
6335 else
6336 Mask.push_back(ExpIndex++);
6337 }
6338 Ops.push_back(ExpVec);
6339 Ops.push_back(PassThru);
6340 return true;
6341 }
6342 default:
6343 llvm_unreachable("unknown target shuffle node");
6344 }
6345
6346 // Empty mask indicates the decode failed.
6347 if (Mask.empty())
6348 return false;
6349
6350 // Check if we're getting a shuffle mask with zero'd elements.
6351 if (!AllowSentinelZero && isAnyZero(Mask))
6352 return false;
6353
6354 // If we have a fake unary shuffle, the shuffle mask is spread across two
6355 // inputs that are actually the same node. Re-map the mask to always point
6356 // into the first input.
6357 if (IsFakeUnary)
6358 for (int &M : Mask)
6359 if (M >= (int)Mask.size())
6360 M -= Mask.size();
6361
6362 // If we didn't already add operands in the opcode-specific code, default to
6363 // adding 1 or 2 operands starting at 0.
6364 if (Ops.empty()) {
6365 Ops.push_back(N.getOperand(0));
6366 if (!IsUnary || IsFakeUnary)
6367 Ops.push_back(N.getOperand(1));
6368 }
6369
6370 return true;
6371}
6372
6373// Wrapper for getTargetShuffleMask with InUnary;
6374static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6376 SmallVectorImpl<int> &Mask) {
6377 bool IsUnary;
6378 return getTargetShuffleMask(N, AllowSentinelZero, Ops, Mask, IsUnary);
6379}
6380
6381/// Compute whether each element of a shuffle is zeroable.
6382///
6383/// A "zeroable" vector shuffle element is one which can be lowered to zero.
6384/// Either it is an undef element in the shuffle mask, the element of the input
6385/// referenced is undef, or the element of the input referenced is known to be
6386/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6387/// as many lanes with this technique as possible to simplify the remaining
6388/// shuffle.
6390 SDValue V1, SDValue V2,
6391 APInt &KnownUndef, APInt &KnownZero) {
6392 int Size = Mask.size();
6393 KnownUndef = KnownZero = APInt::getZero(Size);
6394
6396 V2 = peekThroughBitcasts(V2);
6397
6398 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6399 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6400
6401 int VectorSizeInBits = V1.getValueSizeInBits();
6402 int ScalarSizeInBits = VectorSizeInBits / Size;
6403 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
6404
6405 for (int i = 0; i < Size; ++i) {
6406 int M = Mask[i];
6407 // Handle the easy cases.
6408 if (M < 0) {
6409 KnownUndef.setBit(i);
6410 continue;
6411 }
6412 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6413 KnownZero.setBit(i);
6414 continue;
6415 }
6416
6417 // Determine shuffle input and normalize the mask.
6418 SDValue V = M < Size ? V1 : V2;
6419 M %= Size;
6420
6421 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
6422 if (V.getOpcode() != ISD::BUILD_VECTOR)
6423 continue;
6424
6425 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
6426 // the (larger) source element must be UNDEF/ZERO.
6427 if ((Size % V.getNumOperands()) == 0) {
6428 int Scale = Size / V->getNumOperands();
6429 SDValue Op = V.getOperand(M / Scale);
6430 if (Op.isUndef())
6431 KnownUndef.setBit(i);
6432 if (X86::isZeroNode(Op))
6433 KnownZero.setBit(i);
6434 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
6435 APInt Val = Cst->getAPIntValue();
6436 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6437 if (Val == 0)
6438 KnownZero.setBit(i);
6439 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6440 APInt Val = Cst->getValueAPF().bitcastToAPInt();
6441 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6442 if (Val == 0)
6443 KnownZero.setBit(i);
6444 }
6445 continue;
6446 }
6447
6448 // If the BUILD_VECTOR has more elements then all the (smaller) source
6449 // elements must be UNDEF or ZERO.
6450 if ((V.getNumOperands() % Size) == 0) {
6451 int Scale = V->getNumOperands() / Size;
6452 bool AllUndef = true;
6453 bool AllZero = true;
6454 for (int j = 0; j < Scale; ++j) {
6455 SDValue Op = V.getOperand((M * Scale) + j);
6456 AllUndef &= Op.isUndef();
6457 AllZero &= X86::isZeroNode(Op);
6458 }
6459 if (AllUndef)
6460 KnownUndef.setBit(i);
6461 if (AllZero)
6462 KnownZero.setBit(i);
6463 continue;
6464 }
6465 }
6466}
6467
6468/// Decode a target shuffle mask and inputs and see if any values are
6469/// known to be undef or zero from their inputs.
6470/// Returns true if the target shuffle mask was decoded.
6471/// FIXME: Merge this with computeZeroableShuffleElements?
6474 APInt &KnownUndef, APInt &KnownZero) {
6475 bool IsUnary;
6476 if (!isTargetShuffle(N.getOpcode()))
6477 return false;
6478
6479 MVT VT = N.getSimpleValueType();
6480 if (!getTargetShuffleMask(N, true, Ops, Mask, IsUnary))
6481 return false;
6482
6483 int Size = Mask.size();
6484 SDValue V1 = Ops[0];
6485 SDValue V2 = IsUnary ? V1 : Ops[1];
6486 KnownUndef = KnownZero = APInt::getZero(Size);
6487
6489 V2 = peekThroughBitcasts(V2);
6490
6491 assert((VT.getSizeInBits() % Size) == 0 &&
6492 "Illegal split of shuffle value type");
6493 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
6494
6495 // Extract known constant input data.
6496 APInt UndefSrcElts[2];
6497 SmallVector<APInt, 32> SrcEltBits[2];
6498 bool IsSrcConstant[2] = {
6499 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6500 SrcEltBits[0], /*AllowWholeUndefs*/ true,
6501 /*AllowPartialUndefs*/ false),
6502 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6503 SrcEltBits[1], /*AllowWholeUndefs*/ true,
6504 /*AllowPartialUndefs*/ false)};
6505
6506 for (int i = 0; i < Size; ++i) {
6507 int M = Mask[i];
6508
6509 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6510 if (M < 0) {
6511 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
6512 if (SM_SentinelUndef == M)
6513 KnownUndef.setBit(i);
6514 if (SM_SentinelZero == M)
6515 KnownZero.setBit(i);
6516 continue;
6517 }
6518
6519 // Determine shuffle input and normalize the mask.
6520 unsigned SrcIdx = M / Size;
6521 SDValue V = M < Size ? V1 : V2;
6522 M %= Size;
6523
6524 // We are referencing an UNDEF input.
6525 if (V.isUndef()) {
6526 KnownUndef.setBit(i);
6527 continue;
6528 }
6529
6530 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6531 // TODO: We currently only set UNDEF for integer types - floats use the same
6532 // registers as vectors and many of the scalar folded loads rely on the
6533 // SCALAR_TO_VECTOR pattern.
6534 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6535 (Size % V.getValueType().getVectorNumElements()) == 0) {
6536 int Scale = Size / V.getValueType().getVectorNumElements();
6537 int Idx = M / Scale;
6538 if (Idx != 0 && !VT.isFloatingPoint())
6539 KnownUndef.setBit(i);
6540 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6541 KnownZero.setBit(i);
6542 continue;
6543 }
6544
6545 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
6546 // base vectors.
6547 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
6548 SDValue Vec = V.getOperand(0);
6549 int NumVecElts = Vec.getValueType().getVectorNumElements();
6550 if (Vec.isUndef() && Size == NumVecElts) {
6551 int Idx = V.getConstantOperandVal(2);
6552 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
6553 if (M < Idx || (Idx + NumSubElts) <= M)
6554 KnownUndef.setBit(i);
6555 }
6556 continue;
6557 }
6558
6559 // Attempt to extract from the source's constant bits.
6560 if (IsSrcConstant[SrcIdx]) {
6561 if (UndefSrcElts[SrcIdx][M])
6562 KnownUndef.setBit(i);
6563 else if (SrcEltBits[SrcIdx][M] == 0)
6564 KnownZero.setBit(i);
6565 }
6566 }
6567
6568 assert(VT.getVectorNumElements() == (unsigned)Size &&
6569 "Different mask size from vector size!");
6570 return true;
6571}
6572
6573// Replace target shuffle mask elements with known undef/zero sentinels.
6575 const APInt &KnownUndef,
6576 const APInt &KnownZero,
6577 bool ResolveKnownZeros= true) {
6578 unsigned NumElts = Mask.size();
6579 assert(KnownUndef.getBitWidth() == NumElts &&
6580 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
6581
6582 for (unsigned i = 0; i != NumElts; ++i) {
6583 if (KnownUndef[i])
6584 Mask[i] = SM_SentinelUndef;
6585 else if (ResolveKnownZeros && KnownZero[i])
6586 Mask[i] = SM_SentinelZero;
6587 }
6588}
6589
6590// Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
6592 APInt &KnownUndef,
6593 APInt &KnownZero) {
6594 unsigned NumElts = Mask.size();
6595 KnownUndef = KnownZero = APInt::getZero(NumElts);
6596
6597 for (unsigned i = 0; i != NumElts; ++i) {
6598 int M = Mask[i];
6599 if (SM_SentinelUndef == M)
6600 KnownUndef.setBit(i);
6601 if (SM_SentinelZero == M)
6602 KnownZero.setBit(i);
6603 }
6604}
6605
6606// Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
6608 SDValue Cond, bool IsBLENDV = false) {
6609 EVT CondVT = Cond.getValueType();
6610 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
6611 unsigned NumElts = CondVT.getVectorNumElements();
6612
6613 APInt UndefElts;
6614 SmallVector<APInt, 32> EltBits;
6615 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
6616 /*AllowWholeUndefs*/ true,
6617 /*AllowPartialUndefs*/ false))
6618 return false;
6619
6620 Mask.resize(NumElts, SM_SentinelUndef);
6621
6622 for (int i = 0; i != (int)NumElts; ++i) {
6623 Mask[i] = i;
6624 // Arbitrarily choose from the 2nd operand if the select condition element
6625 // is undef.
6626 // TODO: Can we do better by matching patterns such as even/odd?
6627 if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
6628 (IsBLENDV && EltBits[i].isNonNegative()))
6629 Mask[i] += NumElts;
6630 }
6631
6632 return true;
6633}
6634
6635// Forward declaration (for getFauxShuffleMask recursive check).
6636static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6639 const SelectionDAG &DAG, unsigned Depth,
6640 bool ResolveKnownElts);
6641
6642// Attempt to decode ops that could be represented as a shuffle mask.
6643// The decoded shuffle mask may contain a different number of elements to the
6644// destination value type.
6645// TODO: Merge into getTargetShuffleInputs()
6646static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
6649 const SelectionDAG &DAG, unsigned Depth,
6650 bool ResolveKnownElts) {
6651 Mask.clear();
6652 Ops.clear();
6653
6654 MVT VT = N.getSimpleValueType();
6655 unsigned NumElts = VT.getVectorNumElements();
6656 unsigned NumSizeInBits = VT.getSizeInBits();
6657 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6658 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
6659 return false;
6660 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
6661 unsigned NumSizeInBytes = NumSizeInBits / 8;
6662 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6663
6664 unsigned Opcode = N.getOpcode();
6665 switch (Opcode) {
6666 case ISD::VECTOR_SHUFFLE: {
6667 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6668 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6669 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6670 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6671 Ops.push_back(N.getOperand(0));
6672 Ops.push_back(N.getOperand(1));
6673 return true;
6674 }
6675 return false;
6676 }
6677 case ISD::AND:
6678 case X86ISD::ANDNP: {
6679 // Attempt to decode as a per-byte mask.
6680 APInt UndefElts;
6681 SmallVector<APInt, 32> EltBits;
6682 SDValue N0 = N.getOperand(0);
6683 SDValue N1 = N.getOperand(1);
6684 bool IsAndN = (X86ISD::ANDNP == Opcode);
6685 uint64_t ZeroMask = IsAndN ? 255 : 0;
6686 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits,
6687 /*AllowWholeUndefs*/ false,
6688 /*AllowPartialUndefs*/ false))
6689 return false;
6690 // We can't assume an undef src element gives an undef dst - the other src
6691 // might be zero.
6692 assert(UndefElts.isZero() && "Unexpected UNDEF element in AND/ANDNP mask");
6693 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6694 const APInt &ByteBits = EltBits[i];
6695 if (ByteBits != 0 && ByteBits != 255)
6696 return false;
6697 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6698 }
6699 Ops.push_back(IsAndN ? N1 : N0);
6700 return true;
6701 }
6702 case ISD::OR: {
6703 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6704 // is a valid shuffle index.
6705 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
6706 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
6707 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6708 return false;
6709
6710 SmallVector<int, 64> SrcMask0, SrcMask1;
6711 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6714 if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
6715 Depth + 1, true) ||
6716 !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
6717 Depth + 1, true))
6718 return false;
6719
6720 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6721 SmallVector<int, 64> Mask0, Mask1;
6722 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6723 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6724 for (int i = 0; i != (int)MaskSize; ++i) {
6725 // NOTE: Don't handle demanded SM_SentinelUndef, as we can end up in
6726 // infinite loops converting between OR and BLEND shuffles due to
6727 // canWidenShuffleElements merging away undef elements, meaning we
6728 // fail to recognise the OR as the undef element isn't known zero.
6729 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6730 Mask.push_back(SM_SentinelZero);
6731 else if (Mask1[i] == SM_SentinelZero)
6732 Mask.push_back(i);
6733 else if (Mask0[i] == SM_SentinelZero)
6734 Mask.push_back(i + MaskSize);
6735 else if (MaskSize == NumElts && !DemandedElts[i])
6736 Mask.push_back(SM_SentinelUndef);
6737 else
6738 return false;
6739 }
6740 Ops.push_back(N.getOperand(0));
6741 Ops.push_back(N.getOperand(1));
6742 return true;
6743 }
6744 case ISD::CONCAT_VECTORS: {
6745 // Limit this to vXi64 vector cases to make the most of cross lane shuffles.
6746 unsigned NumSubElts = N.getOperand(0).getValueType().getVectorNumElements();
6747 if (NumBitsPerElt == 64) {
6748 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
6749 for (unsigned M = 0; M != NumSubElts; ++M)
6750 Mask.push_back((I * NumElts) + M);
6751 Ops.push_back(N.getOperand(I));
6752 }
6753 return true;
6754 }
6755 return false;
6756 }
6757 case ISD::INSERT_SUBVECTOR: {
6758 SDValue Src = N.getOperand(0);
6759 SDValue Sub = N.getOperand(1);
6760 EVT SubVT = Sub.getValueType();
6761 unsigned NumSubElts = SubVT.getVectorNumElements();
6762 uint64_t InsertIdx = N.getConstantOperandVal(2);
6763 // Subvector isn't demanded - just return the base vector.
6764 if (DemandedElts.extractBits(NumSubElts, InsertIdx) == 0) {
6765 Mask.resize(NumElts);
6766 std::iota(Mask.begin(), Mask.end(), 0);
6767 Ops.push_back(Src);
6768 return true;
6769 }
6770 // Handle CONCAT(SUB0, SUB1).
6771 // Limit to vXi64/splat cases to make the most of cross lane shuffles.
6772 if (Depth > 0 && InsertIdx == NumSubElts && NumElts == (2 * NumSubElts) &&
6773 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6774 Src.getOperand(0).isUndef() &&
6775 Src.getOperand(1).getValueType() == SubVT &&
6776 Src.getConstantOperandVal(2) == 0 &&
6777 (NumBitsPerElt == 64 || Src.getOperand(1) == Sub) &&
6778 SDNode::areOnlyUsersOf({N.getNode(), Src.getNode()}, Sub.getNode())) {
6779 Mask.resize(NumElts);
6780 std::iota(Mask.begin(), Mask.begin() + NumSubElts, 0);
6781 std::iota(Mask.begin() + NumSubElts, Mask.end(), NumElts);
6782 Ops.push_back(Src.getOperand(1));
6783 Ops.push_back(Sub);
6784 return true;
6785 }
6786 // Handle INSERT_SUBVECTOR(UNDEF, SUB, IDX) iff IDX != 0
6787 if (InsertIdx != 0 && Src.isUndef() &&
6789 Mask.assign(NumElts, SM_SentinelUndef);
6790 std::iota(Mask.begin() + InsertIdx, Mask.begin() + InsertIdx + NumSubElts,
6791 0);
6792 Ops.push_back(Sub);
6793 return true;
6794 }
6795 if (!N->isOnlyUserOf(Sub.getNode()))
6796 return false;
6797
6798 SmallVector<int, 64> SubMask;
6799 SmallVector<SDValue, 2> SubInputs;
6801 EVT SubSrcVT = SubSrc.getValueType();
6802 if (!SubSrcVT.isVector())
6803 return false;
6804
6805 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
6806 if (SubSrc.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6807 SubSrc.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6808 uint64_t ExtractIdx = SubSrc.getConstantOperandVal(1);
6809 SDValue SubSrcSrc = SubSrc.getOperand(0);
6810 unsigned NumSubSrcSrcElts =
6811 SubSrcSrc.getValueType().getVectorNumElements();
6812 unsigned MaxElts = std::max(NumElts, NumSubSrcSrcElts);
6813 assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcSrcElts) == 0 &&
6814 "Subvector valuetype mismatch");
6815 InsertIdx *= (MaxElts / NumElts);
6816 ExtractIdx *= (MaxElts / NumSubSrcSrcElts);
6817 NumSubElts *= (MaxElts / NumElts);
6818 bool SrcIsUndef = Src.isUndef();
6819 for (int i = 0; i != (int)MaxElts; ++i)
6820 Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
6821 for (int i = 0; i != (int)NumSubElts; ++i)
6822 Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
6823 if (!SrcIsUndef)
6824 Ops.push_back(Src);
6825 Ops.push_back(SubSrcSrc);
6826 return true;
6827 }
6828
6829 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6830 APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
6831 if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
6832 Depth + 1, ResolveKnownElts))
6833 return false;
6834
6835 // Subvector shuffle inputs must not be larger than the subvector.
6836 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
6837 return SubVT.getFixedSizeInBits() <
6838 SubInput.getValueSizeInBits().getFixedValue();
6839 }))
6840 return false;
6841
6842 if (SubMask.size() != NumSubElts) {
6843 assert(((SubMask.size() % NumSubElts) == 0 ||
6844 (NumSubElts % SubMask.size()) == 0) &&
6845 "Illegal submask scale");
6846 if ((NumSubElts % SubMask.size()) == 0) {
6847 int Scale = NumSubElts / SubMask.size();
6848 SmallVector<int, 64> ScaledSubMask;
6849 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
6850 SubMask = ScaledSubMask;
6851 } else {
6852 int Scale = SubMask.size() / NumSubElts;
6853 NumSubElts = SubMask.size();
6854 NumElts *= Scale;
6855 InsertIdx *= Scale;
6856 }
6857 }
6858 Ops.push_back(Src);
6859 Ops.append(SubInputs.begin(), SubInputs.end());
6860 if (ISD::isBuildVectorAllZeros(Src.getNode()))
6861 Mask.append(NumElts, SM_SentinelZero);
6862 else
6863 for (int i = 0; i != (int)NumElts; ++i)
6864 Mask.push_back(i);
6865 for (int i = 0; i != (int)NumSubElts; ++i) {
6866 int M = SubMask[i];
6867 if (0 <= M) {
6868 int InputIdx = M / NumSubElts;
6869 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6870 }
6871 Mask[i + InsertIdx] = M;
6872 }
6873 return true;
6874 }
6875 case X86ISD::PINSRB:
6876 case X86ISD::PINSRW:
6879 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
6880 // vector, for matching src/dst vector types.
6881 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
6882
6883 unsigned DstIdx = 0;
6884 if (Opcode != ISD::SCALAR_TO_VECTOR) {
6885 // Check we have an in-range constant insertion index.
6886 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6887 N.getConstantOperandAPInt(2).uge(NumElts))
6888 return false;
6889 DstIdx = N.getConstantOperandVal(2);
6890
6891 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
6892 if (X86::isZeroNode(Scl)) {
6893 Ops.push_back(N.getOperand(0));
6894 for (unsigned i = 0; i != NumElts; ++i)
6895 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
6896 return true;
6897 }
6898 }
6899
6900 // Peek through trunc/aext/zext/bitcast.
6901 // TODO: aext shouldn't require SM_SentinelZero padding.
6902 // TODO: handle shift of scalars.
6903 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
6904 while (Scl.getOpcode() == ISD::TRUNCATE ||
6905 Scl.getOpcode() == ISD::ANY_EXTEND ||
6906 Scl.getOpcode() == ISD::ZERO_EXTEND ||
6907 (Scl.getOpcode() == ISD::BITCAST &&
6910 Scl = Scl.getOperand(0);
6911 MinBitsPerElt =
6912 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
6913 }
6914 if ((MinBitsPerElt % 8) != 0)
6915 return false;
6916
6917 // Attempt to find the source vector the scalar was extracted from.
6918 SDValue SrcExtract;
6919 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
6920 Scl.getOpcode() == X86ISD::PEXTRW ||
6921 Scl.getOpcode() == X86ISD::PEXTRB) &&
6922 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6923 SrcExtract = Scl;
6924 }
6925 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6926 return false;
6927
6928 SDValue SrcVec = SrcExtract.getOperand(0);
6929 EVT SrcVT = SrcVec.getValueType();
6930 if (!SrcVT.getScalarType().isByteSized())
6931 return false;
6932 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6933 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
6934 unsigned DstByte = DstIdx * NumBytesPerElt;
6935 MinBitsPerElt =
6936 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
6937
6938 // Create 'identity' byte level shuffle mask and then add inserted bytes.
6939 if (Opcode == ISD::SCALAR_TO_VECTOR) {
6940 Ops.push_back(SrcVec);
6941 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6942 } else {
6943 Ops.push_back(SrcVec);
6944 Ops.push_back(N.getOperand(0));
6945 for (int i = 0; i != (int)NumSizeInBytes; ++i)
6946 Mask.push_back(NumSizeInBytes + i);
6947 }
6948
6949 unsigned MinBytesPerElts = MinBitsPerElt / 8;
6950 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
6951 for (unsigned i = 0; i != MinBytesPerElts; ++i)
6952 Mask[DstByte + i] = SrcByte + i;
6953 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
6954 Mask[DstByte + i] = SM_SentinelZero;
6955 return true;
6956 }
6957 case X86ISD::PACKSS:
6958 case X86ISD::PACKUS: {
6959 SDValue N0 = N.getOperand(0);
6960 SDValue N1 = N.getOperand(1);
6961 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6962 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6963 "Unexpected input value type");
6964
6965 APInt EltsLHS, EltsRHS;
6966 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
6967
6968 // If we know input saturation won't happen (or we don't care for particular
6969 // lanes), we can treat this as a truncation shuffle.
6970 bool Offset0 = false, Offset1 = false;
6971 if (Opcode == X86ISD::PACKSS) {
6972 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6973 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
6974 (!(N1.isUndef() || EltsRHS.isZero()) &&
6975 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
6976 return false;
6977 // We can't easily fold ASHR into a shuffle, but if it was feeding a
6978 // PACKSS then it was likely being used for sign-extension for a
6979 // truncation, so just peek through and adjust the mask accordingly.
6980 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
6981 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
6982 Offset0 = true;
6983 N0 = N0.getOperand(0);
6984 }
6985 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
6986 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
6987 Offset1 = true;
6988 N1 = N1.getOperand(0);
6989 }
6990 } else {
6991 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6992 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6993 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
6994 (!(N1.isUndef() || EltsRHS.isZero()) &&
6995 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
6996 return false;
6997 }
6998
6999 bool IsUnary = (N0 == N1);
7000
7001 Ops.push_back(N0);
7002 if (!IsUnary)
7003 Ops.push_back(N1);
7004
7005 createPackShuffleMask(VT, Mask, IsUnary);
7006
7007 if (Offset0 || Offset1) {
7008 for (int &M : Mask)
7009 if ((Offset0 && isInRange(M, 0, NumElts)) ||
7010 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
7011 ++M;
7012 }
7013 return true;
7014 }
7015 case ISD::VSELECT:
7016 case X86ISD::BLENDV: {
7017 SDValue Cond = N.getOperand(0);
7018 if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
7019 Ops.push_back(N.getOperand(1));
7020 Ops.push_back(N.getOperand(2));
7021 return true;
7022 }
7023 return false;
7024 }
7025 case X86ISD::VTRUNC: {
7026 SDValue Src = N.getOperand(0);
7027 EVT SrcVT = Src.getValueType();
7028 if (SrcVT.getSizeInBits() != NumSizeInBits)
7029 return false;
7030 unsigned NumSrcElts = SrcVT.getVectorNumElements();
7031 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7032 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
7033 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
7034 for (unsigned i = 0; i != NumSrcElts; ++i)
7035 Mask.push_back(i * Scale);
7036 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
7037 Ops.push_back(Src);
7038 return true;
7039 }
7040 case ISD::SHL:
7041 case ISD::SRL: {
7042 APInt UndefElts;
7043 SmallVector<APInt, 32> EltBits;
7044 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7045 UndefElts, EltBits,
7046 /*AllowWholeUndefs*/ true,
7047 /*AllowPartialUndefs*/ false))
7048 return false;
7049
7050 // We can only decode 'whole byte' bit shifts as shuffles.
7051 for (unsigned I = 0; I != NumElts; ++I)
7052 if (DemandedElts[I] && !UndefElts[I] &&
7053 (EltBits[I].urem(8) != 0 || EltBits[I].uge(NumBitsPerElt)))
7054 return false;
7055
7056 Mask.append(NumSizeInBytes, SM_SentinelUndef);
7057 Ops.push_back(N.getOperand(0));
7058
7059 for (unsigned I = 0; I != NumElts; ++I) {
7060 if (!DemandedElts[I] || UndefElts[I])
7061 continue;
7062 unsigned ByteShift = EltBits[I].getZExtValue() / 8;
7063 unsigned Lo = I * NumBytesPerElt;
7064 unsigned Hi = Lo + NumBytesPerElt;
7065 // Clear mask to all zeros and insert the shifted byte indices.
7066 std::fill(Mask.begin() + Lo, Mask.begin() + Hi, SM_SentinelZero);
7067 if (ISD::SHL == Opcode)
7068 std::iota(Mask.begin() + Lo + ByteShift, Mask.begin() + Hi, Lo);
7069 else
7070 std::iota(Mask.begin() + Lo, Mask.begin() + Hi - ByteShift,
7071 Lo + ByteShift);
7072 }
7073 return true;
7074 }
7075 case X86ISD::VSHLI:
7076 case X86ISD::VSRLI: {
7077 uint64_t ShiftVal = N.getConstantOperandVal(1);
7078 // Out of range bit shifts are guaranteed to be zero.
7079 if (NumBitsPerElt <= ShiftVal) {
7080 Mask.append(NumElts, SM_SentinelZero);
7081 return true;
7082 }
7083
7084 // We can only decode 'whole byte' bit shifts as shuffles.
7085 if ((ShiftVal % 8) != 0)
7086 break;
7087
7088 uint64_t ByteShift = ShiftVal / 8;
7089 Ops.push_back(N.getOperand(0));
7090
7091 // Clear mask to all zeros and insert the shifted byte indices.
7092 Mask.append(NumSizeInBytes, SM_SentinelZero);
7093
7094 if (X86ISD::VSHLI == Opcode) {
7095 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7096 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7097 Mask[i + j] = i + j - ByteShift;
7098 } else {
7099 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7100 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7101 Mask[i + j - ByteShift] = i + j;
7102 }
7103 return true;
7104 }
7105 case ISD::ROTL:
7106 case ISD::ROTR: {
7107 APInt UndefElts;
7108 SmallVector<APInt, 32> EltBits;
7109 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7110 UndefElts, EltBits,
7111 /*AllowWholeUndefs*/ true,
7112 /*AllowPartialUndefs*/ false))
7113 return false;
7114
7115 // We can only decode 'whole byte' bit rotates as shuffles.
7116 for (unsigned I = 0; I != NumElts; ++I)
7117 if (DemandedElts[I] && !UndefElts[I] &&
7118 (EltBits[I].urem(NumBitsPerElt) % 8) != 0)
7119 return false;
7120
7121 Ops.push_back(N.getOperand(0));
7122 for (unsigned I = 0; I != NumElts; ++I) {
7123 if (!DemandedElts[I] || UndefElts[I]) {
7124 Mask.append(NumBytesPerElt, SM_SentinelUndef);
7125 continue;
7126 }
7127 int Offset = EltBits[I].urem(NumBitsPerElt) / 8;
7128 Offset = (ISD::ROTL == Opcode ? NumBytesPerElt - Offset : Offset);
7129 int BaseIdx = I * NumBytesPerElt;
7130 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7131 Mask.push_back(BaseIdx + ((Offset + J) % NumBytesPerElt));
7132 }
7133 }
7134 return true;
7135 }
7136 case X86ISD::VROTLI:
7137 case X86ISD::VROTRI: {
7138 // We can only decode 'whole byte' bit rotates as shuffles.
7139 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7140 if ((RotateVal % 8) != 0)
7141 return false;
7142 Ops.push_back(N.getOperand(0));
7143 int Offset = RotateVal / 8;
7144 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7145 for (int i = 0; i != (int)NumElts; ++i) {
7146 int BaseIdx = i * NumBytesPerElt;
7147 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7148 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7149 }
7150 }
7151 return true;
7152 }
7153 case X86ISD::VSHLD:
7154 case X86ISD::VSHRD: {
7155 // We can only decode 'whole byte' bit funnel shifts as shuffles.
7156 uint64_t ShiftVal = N.getConstantOperandAPInt(2).urem(NumBitsPerElt);
7157 int Offset = ShiftVal / 8;
7158 if ((ShiftVal % 8) != 0 || Offset == 0)
7159 return false;
7160 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 1 : 0));
7161 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 0 : 1));
7162 Offset = X86ISD::VSHRD == Opcode ? (NumBytesPerElt - Offset) : Offset;
7163 for (int I = 0; I != (int)NumElts; ++I) {
7164 int BaseIdx = (I * NumBytesPerElt) - Offset;
7165 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7166 int MaskIdx = BaseIdx + J;
7167 MaskIdx += J < Offset ? (NumSizeInBytes + NumBytesPerElt) : 0;
7168 Mask.push_back(MaskIdx);
7169 }
7170 }
7171 return true;
7172 }
7173 case X86ISD::VBROADCAST: {
7174 SDValue Src = N.getOperand(0);
7175 if (!Src.getSimpleValueType().isVector()) {
7176 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7177 !isNullConstant(Src.getOperand(1)) ||
7178 Src.getOperand(0).getValueType().getScalarType() !=
7179 VT.getScalarType())
7180 return false;
7181 Src = Src.getOperand(0);
7182 }
7183 Ops.push_back(Src);
7184 Mask.append(NumElts, 0);
7185 return true;
7186 }
7188 SDValue Src = N.getOperand(0);
7189 EVT SrcVT = Src.getValueType();
7190 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7191
7192 // Extended source must be a simple vector.
7193 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7194 (NumBitsPerSrcElt % 8) != 0)
7195 return false;
7196
7197 // We can only handle all-signbits extensions.
7198 APInt DemandedSrcElts =
7199 DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
7200 if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
7201 return false;
7202
7203 assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
7204 unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
7205 for (unsigned I = 0; I != NumElts; ++I)
7206 Mask.append(Scale, I);
7207 Ops.push_back(Src);
7208 return true;
7209 }
7210 case ISD::ZERO_EXTEND:
7211 case ISD::ANY_EXTEND:
7214 SDValue Src = N.getOperand(0);
7215 EVT SrcVT = Src.getValueType();
7216
7217 // Extended source must be a simple vector.
7218 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7219 (SrcVT.getScalarSizeInBits() % 8) != 0)
7220 return false;
7221
7222 bool IsAnyExtend =
7223 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7224 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7225 IsAnyExtend, Mask);
7226 Ops.push_back(Src);
7227 return true;
7228 }
7229 }
7230
7231 return false;
7232}
7233
7234/// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7236 SmallVectorImpl<int> &Mask) {
7237 int MaskWidth = Mask.size();
7238 SmallVector<SDValue, 16> UsedInputs;
7239 for (int i = 0, e = Inputs.size(); i < e; ++i) {
7240 int lo = UsedInputs.size() * MaskWidth;
7241 int hi = lo + MaskWidth;
7242
7243 // Strip UNDEF input usage.
7244 if (Inputs[i].isUndef())
7245 for (int &M : Mask)
7246 if ((lo <= M) && (M < hi))
7247 M = SM_SentinelUndef;
7248
7249 // Check for unused inputs.
7250 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7251 for (int &M : Mask)
7252 if (lo <= M)
7253 M -= MaskWidth;
7254 continue;
7255 }
7256
7257 // Check for repeated inputs.
7258 bool IsRepeat = false;
7259 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7260 if (peekThroughBitcasts(UsedInputs[j]) != peekThroughBitcasts(Inputs[i]))
7261 continue;
7262 for (int &M : Mask)
7263 if (lo <= M)
7264 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7265 IsRepeat = true;
7266 break;
7267 }
7268 if (IsRepeat)
7269 continue;
7270
7271 UsedInputs.push_back(Inputs[i]);
7272 }
7273 Inputs = std::move(UsedInputs);
7274}
7275
7276/// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7277/// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7278/// Returns true if the target shuffle mask was decoded.
7279static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7282 APInt &KnownUndef, APInt &KnownZero,
7283 const SelectionDAG &DAG, unsigned Depth,
7284 bool ResolveKnownElts) {
7286 return false; // Limit search depth.
7287
7288 EVT VT = Op.getValueType();
7289 if (!VT.isSimple() || !VT.isVector())
7290 return false;
7291
7292 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7293 if (ResolveKnownElts)
7294 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7295 return true;
7296 }
7297 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7298 ResolveKnownElts)) {
7299 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7300 return true;
7301 }
7302 return false;
7303}
7304
7305static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7308 const SelectionDAG &DAG, unsigned Depth,
7309 bool ResolveKnownElts) {
7310 APInt KnownUndef, KnownZero;
7311 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7312 KnownZero, DAG, Depth, ResolveKnownElts);
7313}
7314
7317 const SelectionDAG &DAG, unsigned Depth = 0,
7318 bool ResolveKnownElts = true) {
7319 EVT VT = Op.getValueType();
7320 if (!VT.isSimple() || !VT.isVector())
7321 return false;
7322
7323 unsigned NumElts = Op.getValueType().getVectorNumElements();
7324 APInt DemandedElts = APInt::getAllOnes(NumElts);
7325 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
7326 ResolveKnownElts);
7327}
7328
7329// Attempt to create a scalar/subvector broadcast from the base MemSDNode.
7330static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
7331 EVT MemVT, MemSDNode *Mem, unsigned Offset,
7332 SelectionDAG &DAG) {
7333 assert((Opcode == X86ISD::VBROADCAST_LOAD ||
7334 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
7335 "Unknown broadcast load type");
7336
7337 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
7338 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
7339 return SDValue();
7340
7341 SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
7343 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7344 SDValue Ops[] = {Mem->getChain(), Ptr};
7345 SDValue BcstLd = DAG.getMemIntrinsicNode(
7346 Opcode, DL, Tys, Ops, MemVT,
7348 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
7349 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
7350 return BcstLd;
7351}
7352
7353/// Returns the scalar element that will make up the i'th
7354/// element of the result of the vector shuffle.
7355static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7356 SelectionDAG &DAG, unsigned Depth) {
7358 return SDValue(); // Limit search depth.
7359
7360 EVT VT = Op.getValueType();
7361 unsigned Opcode = Op.getOpcode();
7362 unsigned NumElems = VT.getVectorNumElements();
7363
7364 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7365 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7366 int Elt = SV->getMaskElt(Index);
7367
7368 if (Elt < 0)
7369 return DAG.getUNDEF(VT.getVectorElementType());
7370
7371 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7372 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7373 }
7374
7375 // Recurse into target specific vector shuffles to find scalars.
7376 if (isTargetShuffle(Opcode)) {
7377 MVT ShufVT = VT.getSimpleVT();
7378 MVT ShufSVT = ShufVT.getVectorElementType();
7379 int NumElems = (int)ShufVT.getVectorNumElements();
7380 SmallVector<int, 16> ShuffleMask;
7382 if (!getTargetShuffleMask(Op, true, ShuffleOps, ShuffleMask))
7383 return SDValue();
7384
7385 int Elt = ShuffleMask[Index];
7386 if (Elt == SM_SentinelZero)
7387 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7388 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7389 if (Elt == SM_SentinelUndef)
7390 return DAG.getUNDEF(ShufSVT);
7391
7392 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7393 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7394 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7395 }
7396
7397 // Recurse into insert_subvector base/sub vector to find scalars.
7398 if (Opcode == ISD::INSERT_SUBVECTOR) {
7399 SDValue Vec = Op.getOperand(0);
7400 SDValue Sub = Op.getOperand(1);
7401 uint64_t SubIdx = Op.getConstantOperandVal(2);
7402 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7403
7404 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7405 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7406 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7407 }
7408
7409 // Recurse into concat_vectors sub vector to find scalars.
7410 if (Opcode == ISD::CONCAT_VECTORS) {
7411 EVT SubVT = Op.getOperand(0).getValueType();
7412 unsigned NumSubElts = SubVT.getVectorNumElements();
7413 uint64_t SubIdx = Index / NumSubElts;
7414 uint64_t SubElt = Index % NumSubElts;
7415 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
7416 }
7417
7418 // Recurse into extract_subvector src vector to find scalars.
7419 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
7420 SDValue Src = Op.getOperand(0);
7421 uint64_t SrcIdx = Op.getConstantOperandVal(1);
7422 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
7423 }
7424
7425 // We only peek through bitcasts of the same vector width.
7426 if (Opcode == ISD::BITCAST) {
7427 SDValue Src = Op.getOperand(0);
7428 EVT SrcVT = Src.getValueType();
7429 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
7430 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
7431 return SDValue();
7432 }
7433
7434 // Actual nodes that may contain scalar elements
7435
7436 // For insert_vector_elt - either return the index matching scalar or recurse
7437 // into the base vector.
7438 if (Opcode == ISD::INSERT_VECTOR_ELT &&
7439 isa<ConstantSDNode>(Op.getOperand(2))) {
7440 if (Op.getConstantOperandAPInt(2) == Index)
7441 return Op.getOperand(1);
7442 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
7443 }
7444
7445 if (Opcode == ISD::SCALAR_TO_VECTOR)
7446 return (Index == 0) ? Op.getOperand(0)
7447 : DAG.getUNDEF(VT.getVectorElementType());
7448
7449 if (Opcode == ISD::BUILD_VECTOR)
7450 return Op.getOperand(Index);
7451
7452 return SDValue();
7453}
7454
7455// Use PINSRB/PINSRW/PINSRD to create a build vector.
7457 const APInt &NonZeroMask,
7458 unsigned NumNonZero, unsigned NumZero,
7459 SelectionDAG &DAG,
7460 const X86Subtarget &Subtarget) {
7461 MVT VT = Op.getSimpleValueType();
7462 unsigned NumElts = VT.getVectorNumElements();
7463 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7464 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7465 "Illegal vector insertion");
7466
7467 SDValue V;
7468 bool First = true;
7469
7470 for (unsigned i = 0; i < NumElts; ++i) {
7471 bool IsNonZero = NonZeroMask[i];
7472 if (!IsNonZero)
7473 continue;
7474
7475 // If the build vector contains zeros or our first insertion is not the
7476 // first index then insert into zero vector to break any register
7477 // dependency else use SCALAR_TO_VECTOR.
7478 if (First) {
7479 First = false;
7480 if (NumZero || 0 != i)
7481 V = getZeroVector(VT, Subtarget, DAG, DL);
7482 else {
7483 assert(0 == i && "Expected insertion into zero-index");
7484 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7485 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7486 V = DAG.getBitcast(VT, V);
7487 continue;
7488 }
7489 }
7490 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, V, Op.getOperand(i),
7491 DAG.getVectorIdxConstant(i, DL));
7492 }
7493
7494 return V;
7495}
7496
7497/// Custom lower build_vector of v16i8.
7499 const APInt &NonZeroMask,
7500 unsigned NumNonZero, unsigned NumZero,
7501 SelectionDAG &DAG,
7502 const X86Subtarget &Subtarget) {
7503 if (NumNonZero > 8 && !Subtarget.hasSSE41())
7504 return SDValue();
7505
7506 // SSE4.1 - use PINSRB to insert each byte directly.
7507 if (Subtarget.hasSSE41())
7508 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero,
7509 DAG, Subtarget);
7510
7511 SDValue V;
7512
7513 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7514 // If both the lowest 16-bits are non-zero, then convert to MOVD.
7515 if (!NonZeroMask.extractBits(2, 0).isZero() &&
7516 !NonZeroMask.extractBits(2, 2).isZero()) {
7517 for (unsigned I = 0; I != 4; ++I) {
7518 if (!NonZeroMask[I])
7519 continue;
7520 SDValue Elt = DAG.getZExtOrTrunc(Op.getOperand(I), DL, MVT::i32);
7521 if (I != 0)
7522 Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt,
7523 DAG.getConstant(I * 8, DL, MVT::i8));
7524 V = V ? DAG.getNode(ISD::OR, DL, MVT::i32, V, Elt) : Elt;
7525 }
7526 assert(V && "Failed to fold v16i8 vector to zero");
7527 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7528 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32, V);
7529 V = DAG.getBitcast(MVT::v8i16, V);
7530 }
7531 for (unsigned i = V ? 4 : 0; i < 16; i += 2) {
7532 bool ThisIsNonZero = NonZeroMask[i];
7533 bool NextIsNonZero = NonZeroMask[i + 1];
7534 if (!ThisIsNonZero && !NextIsNonZero)
7535 continue;
7536
7537 SDValue Elt;
7538 if (ThisIsNonZero) {
7539 if (NumZero || NextIsNonZero)
7540 Elt = DAG.getZExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7541 else
7542 Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7543 }
7544
7545 if (NextIsNonZero) {
7546 SDValue NextElt = Op.getOperand(i + 1);
7547 if (i == 0 && NumZero)
7548 NextElt = DAG.getZExtOrTrunc(NextElt, DL, MVT::i32);
7549 else
7550 NextElt = DAG.getAnyExtOrTrunc(NextElt, DL, MVT::i32);
7551 NextElt = DAG.getNode(ISD::SHL, DL, MVT::i32, NextElt,
7552 DAG.getConstant(8, DL, MVT::i8));
7553 if (ThisIsNonZero)
7554 Elt = DAG.getNode(ISD::OR, DL, MVT::i32, NextElt, Elt);
7555 else
7556 Elt = NextElt;
7557 }
7558
7559 // If our first insertion is not the first index or zeros are needed, then
7560 // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
7561 // elements undefined).
7562 if (!V) {
7563 if (i != 0 || NumZero)
7564 V = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7565 else {
7566 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, Elt);
7567 V = DAG.getBitcast(MVT::v8i16, V);
7568 continue;
7569 }
7570 }
7571 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
7572 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16, V, Elt,
7573 DAG.getVectorIdxConstant(i / 2, DL));
7574 }
7575
7576 return DAG.getBitcast(MVT::v16i8, V);
7577}
7578
7579/// Custom lower build_vector of v8i16.
7581 const APInt &NonZeroMask,
7582 unsigned NumNonZero, unsigned NumZero,
7583 SelectionDAG &DAG,
7584 const X86Subtarget &Subtarget) {
7585 if (NumNonZero > 4 && !Subtarget.hasSSE41())
7586 return SDValue();
7587
7588 // Use PINSRW to insert each byte directly.
7589 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero, DAG,
7590 Subtarget);
7591}
7592
7593/// Custom lower build_vector of v4i32 or v4f32.
7595 SelectionDAG &DAG,
7596 const X86Subtarget &Subtarget) {
7597 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
7598 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
7599 // Because we're creating a less complicated build vector here, we may enable
7600 // further folding of the MOVDDUP via shuffle transforms.
7601 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
7602 Op.getOperand(0) == Op.getOperand(2) &&
7603 Op.getOperand(1) == Op.getOperand(3) &&
7604 Op.getOperand(0) != Op.getOperand(1)) {
7605 MVT VT = Op.getSimpleValueType();
7606 MVT EltVT = VT.getVectorElementType();
7607 // Create a new build vector with the first 2 elements followed by undef
7608 // padding, bitcast to v2f64, duplicate, and bitcast back.
7609 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
7610 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
7611 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7612 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7613 return DAG.getBitcast(VT, Dup);
7614 }
7615
7616 // Find all zeroable elements.
7617 std::bitset<4> Zeroable, Undefs;
7618 for (int i = 0; i < 4; ++i) {
7619 SDValue Elt = Op.getOperand(i);
7620 Undefs[i] = Elt.isUndef();
7621 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7622 }
7623 assert(Zeroable.size() - Zeroable.count() > 1 &&
7624 "We expect at least two non-zero elements!");
7625
7626 // We only know how to deal with build_vector nodes where elements are either
7627 // zeroable or extract_vector_elt with constant index.
7628 SDValue FirstNonZero;
7629 unsigned FirstNonZeroIdx;
7630 for (unsigned i = 0; i < 4; ++i) {
7631 if (Zeroable[i])
7632 continue;
7633 SDValue Elt = Op.getOperand(i);
7634 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7636 return SDValue();
7637 // Make sure that this node is extracting from a 128-bit vector.
7638 MVT VT = Elt.getOperand(0).getSimpleValueType();
7639 if (!VT.is128BitVector())
7640 return SDValue();
7641 if (!FirstNonZero.getNode()) {
7642 FirstNonZero = Elt;
7643 FirstNonZeroIdx = i;
7644 }
7645 }
7646
7647 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
7648 SDValue V1 = FirstNonZero.getOperand(0);
7649 MVT VT = V1.getSimpleValueType();
7650
7651 // See if this build_vector can be lowered as a blend with zero.
7652 SDValue Elt;
7653 unsigned EltMaskIdx, EltIdx;
7654 int Mask[4];
7655 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7656 if (Zeroable[EltIdx]) {
7657 // The zero vector will be on the right hand side.
7658 Mask[EltIdx] = EltIdx+4;
7659 continue;
7660 }
7661
7662 Elt = Op->getOperand(EltIdx);
7663 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7664 EltMaskIdx = Elt.getConstantOperandVal(1);
7665 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7666 break;
7667 Mask[EltIdx] = EltIdx;
7668 }
7669
7670 if (EltIdx == 4) {
7671 // Let the shuffle legalizer deal with blend operations.
7672 SDValue VZeroOrUndef = (Zeroable == Undefs)
7673 ? DAG.getUNDEF(VT)
7674 : getZeroVector(VT, Subtarget, DAG, DL);
7675 if (V1.getSimpleValueType() != VT)
7676 V1 = DAG.getBitcast(VT, V1);
7677 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
7678 }
7679
7680 // See if we can lower this build_vector to a INSERTPS.
7681 if (!Subtarget.hasSSE41())
7682 return SDValue();
7683
7684 SDValue V2 = Elt.getOperand(0);
7685 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7686 V1 = SDValue();
7687
7688 bool CanFold = true;
7689 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7690 if (Zeroable[i])
7691 continue;
7692
7693 SDValue Current = Op->getOperand(i);
7694 SDValue SrcVector = Current->getOperand(0);
7695 if (!V1.getNode())
7696 V1 = SrcVector;
7697 CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
7698 }
7699
7700 if (!CanFold)
7701 return SDValue();
7702
7703 assert(V1.getNode() && "Expected at least two non-zero elements!");
7704 if (V1.getSimpleValueType() != MVT::v4f32)
7705 V1 = DAG.getBitcast(MVT::v4f32, V1);
7706 if (V2.getSimpleValueType() != MVT::v4f32)
7707 V2 = DAG.getBitcast(MVT::v4f32, V2);
7708
7709 // Ok, we can emit an INSERTPS instruction.
7710 unsigned ZMask = Zeroable.to_ulong();
7711
7712 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7713 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7714 SDValue Result =
7715 DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7716 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
7717 return DAG.getBitcast(VT, Result);
7718}
7719
7720/// Return a vector logical shift node.
7721static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7722 SelectionDAG &DAG, const TargetLowering &TLI,
7723 const SDLoc &dl) {
7724 assert(VT.is128BitVector() && "Unknown type for VShift");
7725 MVT ShVT = MVT::v16i8;
7726 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7727 SrcOp = DAG.getBitcast(ShVT, SrcOp);
7728 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
7729 SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
7730 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7731}
7732
7734 SelectionDAG &DAG) {
7735
7736 // Check if the scalar load can be widened into a vector load. And if
7737 // the address is "base + cst" see if the cst can be "absorbed" into
7738 // the shuffle mask.
7740 SDValue Ptr = LD->getBasePtr();
7741 if (!ISD::isNormalLoad(LD) || !LD->isSimple())
7742 return SDValue();
7743 EVT PVT = LD->getValueType(0);
7744 if (PVT != MVT::i32 && PVT != MVT::f32)
7745 return SDValue();
7746
7747 int FI = -1;
7748 int64_t Offset = 0;
7749 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7750 FI = FINode->getIndex();
7751 Offset = 0;
7752 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7754 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7756 Ptr = Ptr.getOperand(0);
7757 } else {
7758 return SDValue();
7759 }
7760
7761 // FIXME: 256-bit vector instructions don't require a strict alignment,
7762 // improve this code to support it better.
7763 Align RequiredAlign(VT.getSizeInBits() / 8);
7764 SDValue Chain = LD->getChain();
7765 // Make sure the stack object alignment is at least 16 or 32.
7767 MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
7768 if (!InferredAlign || *InferredAlign < RequiredAlign) {
7769 if (MFI.isFixedObjectIndex(FI)) {
7770 // Can't change the alignment. FIXME: It's possible to compute
7771 // the exact stack offset and reference FI + adjust offset instead.
7772 // If someone *really* cares about this. That's the way to implement it.
7773 return SDValue();
7774 } else {
7775 MFI.setObjectAlignment(FI, RequiredAlign);
7776 }
7777 }
7778
7779 // (Offset % 16 or 32) must be multiple of 4. Then address is then
7780 // Ptr + (Offset & ~15).
7781 if (Offset < 0)
7782 return SDValue();
7783 if ((Offset % RequiredAlign.value()) & 3)
7784 return SDValue();
7785 int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
7786 if (StartOffset) {
7787 SDLoc DL(Ptr);
7788 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7789 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7790 }
7791
7792 int EltNo = (Offset - StartOffset) >> 2;
7793 unsigned NumElems = VT.getVectorNumElements();
7794
7795 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
7796 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
7797 LD->getPointerInfo().getWithOffset(StartOffset));
7798
7799 SmallVector<int, 8> Mask(NumElems, EltNo);
7800
7801 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
7802 }
7803
7804 return SDValue();
7805}
7806
7807// Recurse to find a LoadSDNode source and the accumulated ByteOffest.
7808static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
7809 if (ISD::isNON_EXTLoad(Elt.getNode())) {
7810 auto *BaseLd = cast<LoadSDNode>(Elt);
7811 if (!BaseLd->isSimple())
7812 return false;
7813 Ld = BaseLd;
7814 ByteOffset = 0;
7815 return true;
7816 }
7817
7818 switch (Elt.getOpcode()) {
7819 case ISD::BITCAST:
7820 case ISD::TRUNCATE:
7822 return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
7823 case ISD::SRL:
7824 if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7825 uint64_t Amt = AmtC->getZExtValue();
7826 if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
7827 ByteOffset += Amt / 8;
7828 return true;
7829 }
7830 }
7831 break;
7833 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7834 SDValue Src = Elt.getOperand(0);
7835 unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
7836 unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
7837 if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
7838 findEltLoadSrc(Src, Ld, ByteOffset)) {
7839 uint64_t Idx = IdxC->getZExtValue();
7840 ByteOffset += Idx * (SrcSizeInBits / 8);
7841 return true;
7842 }
7843 }
7844 break;
7845 }
7846
7847 return false;
7848}
7849
7850/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7851/// elements can be replaced by a single large load which has the same value as
7852/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7853///
7854/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
7856 const SDLoc &DL, SelectionDAG &DAG,
7857 const X86Subtarget &Subtarget,
7858 bool IsAfterLegalize,
7859 unsigned Depth = 0) {
7861 return SDValue(); // Limit search depth.
7862 if ((VT.getScalarSizeInBits() % 8) != 0)
7863 return SDValue();
7864
7865 // If all of these are oneuse frozen loads, then attempt to create a frozen
7866 // consecutive load.
7867 if (all_of(Elts, [](SDValue Elt) {
7868 return Elt.getOpcode() == ISD::FREEZE &&
7870 Elt.hasOneUse();
7871 })) {
7873 for (SDValue Elt : Elts)
7874 SrcElts.push_back(peekThroughFreeze(Elt));
7875 if (SDValue LD = EltsFromConsecutiveLoads(VT, SrcElts, DL, DAG, Subtarget,
7876 IsAfterLegalize, Depth + 1))
7877 return DAG.getFreeze(LD);
7878 return SDValue();
7879 }
7880
7881 unsigned NumElems = Elts.size();
7882
7883 int LastLoadedElt = -1;
7884 APInt LoadMask = APInt::getZero(NumElems);
7885 APInt ZeroMask = APInt::getZero(NumElems);
7886 APInt UndefMask = APInt::getZero(NumElems);
7887
7888 SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
7889 SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
7890
7891 // For each element in the initializer, see if we've found a load, zero or an
7892 // undef.
7893 for (unsigned i = 0; i < NumElems; ++i) {
7894 SDValue Elt = peekThroughBitcasts(Elts[i]);
7895 if (!Elt.getNode())
7896 return SDValue();
7897 if (Elt.isUndef()) {
7898 UndefMask.setBit(i);
7899 continue;
7900 }
7902 ZeroMask.setBit(i);
7903 continue;
7904 }
7905
7906 // Each loaded element must be the correct fractional portion of the
7907 // requested vector load.
7908 unsigned EltSizeInBits = Elt.getValueSizeInBits();
7909 if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
7910 return SDValue();
7911
7912 if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
7913 return SDValue();
7914 unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
7915 if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
7916 return SDValue();
7917
7918 LoadMask.setBit(i);
7919 LastLoadedElt = i;
7920 }
7921 assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
7922 NumElems &&
7923 "Incomplete element masks");
7924
7925 // Handle Special Cases - all undef or undef/zero.
7926 if (UndefMask.popcount() == NumElems)
7927 return DAG.getUNDEF(VT);
7928 if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
7929 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7930 : DAG.getConstantFP(0.0, DL, VT);
7931
7933 int FirstLoadedElt = LoadMask.countr_zero();
7934 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7935 EVT EltBaseVT = EltBase.getValueType();
7936 assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
7937 "Register/Memory size mismatch");
7938 LoadSDNode *LDBase = Loads[FirstLoadedElt];
7939 assert(LDBase && "Did not find base load for merging consecutive loads");
7940 unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
7941 unsigned BaseSizeInBytes = BaseSizeInBits / 8;
7942 int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
7943 int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
7944 assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
7945
7946 // TODO: Support offsetting the base load.
7947 if (ByteOffsets[FirstLoadedElt] != 0)
7948 return SDValue();
7949
7950 // Check to see if the element's load is consecutive to the base load
7951 // or offset from a previous (already checked) load.
7952 auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
7953 LoadSDNode *Ld = Loads[EltIdx];
7954 int64_t ByteOffset = ByteOffsets[EltIdx];
7955 if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
7956 int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
7957 return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
7958 Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
7959 }
7960 int Stride = EltIdx - FirstLoadedElt;
7961 if (DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes, Stride))
7962 return true;
7963 // Try again using the memory load size (we might have broken a large load
7964 // into smaller elements), ensure the stride is the full memory load size
7965 // apart and a whole number of elements fit in each memory load.
7966 unsigned BaseMemSizeInBits = Base->getMemoryVT().getSizeInBits();
7967 if (((Stride * BaseSizeInBits) % BaseMemSizeInBits) == 0 &&
7968 (BaseMemSizeInBits % BaseSizeInBits) == 0) {
7969 unsigned Scale = BaseMemSizeInBits / BaseSizeInBits;
7970 return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseMemSizeInBits / 8,
7971 Stride / Scale);
7972 }
7973 return false;
7974 };
7975
7976 // Consecutive loads can contain UNDEFS but not ZERO elements.
7977 // Consecutive loads with UNDEFs and ZEROs elements require a
7978 // an additional shuffle stage to clear the ZERO elements.
7979 bool IsConsecutiveLoad = true;
7980 bool IsConsecutiveLoadWithZeros = true;
7981 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7982 if (LoadMask[i]) {
7983 if (!CheckConsecutiveLoad(LDBase, i)) {
7984 IsConsecutiveLoad = false;
7985 IsConsecutiveLoadWithZeros = false;
7986 break;
7987 }
7988 } else if (ZeroMask[i]) {
7989 IsConsecutiveLoad = false;
7990 }
7991 }
7992
7993 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7994 auto MMOFlags = LDBase->getMemOperand()->getFlags();
7995 assert(LDBase->isSimple() &&
7996 "Cannot merge volatile or atomic loads.");
7997 SDValue NewLd =
7998 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7999 LDBase->getPointerInfo(), LDBase->getBaseAlign(), MMOFlags);
8000 for (auto *LD : Loads)
8001 if (LD)
8002 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
8003 return NewLd;
8004 };
8005
8006 // Check if the base load is entirely dereferenceable.
8007 bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
8008 VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
8009
8010 // LOAD - all consecutive load/undefs (must start/end with a load or be
8011 // entirely dereferenceable). If we have found an entire vector of loads and
8012 // undefs, then return a large load of the entire vector width starting at the
8013 // base pointer. If the vector contains zeros, then attempt to shuffle those
8014 // elements.
8015 if (FirstLoadedElt == 0 &&
8016 (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
8017 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8018 if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8019 return SDValue();
8020
8021 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8022 // will lower to regular temporal loads and use the cache.
8023 if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
8024 VT.is256BitVector() && !Subtarget.hasInt256())
8025 return SDValue();
8026
8027 if (NumElems == 1)
8028 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8029
8030 if (!ZeroMask)
8031 return CreateLoad(VT, LDBase);
8032
8033 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8034 // vector and a zero vector to clear out the zero elements.
8035 if (!IsAfterLegalize && VT.isVector()) {
8036 unsigned NumMaskElts = VT.getVectorNumElements();
8037 if ((NumMaskElts % NumElems) == 0) {
8038 unsigned Scale = NumMaskElts / NumElems;
8039 SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8040 for (unsigned i = 0; i < NumElems; ++i) {
8041 if (UndefMask[i])
8042 continue;
8043 int Offset = ZeroMask[i] ? NumMaskElts : 0;
8044 for (unsigned j = 0; j != Scale; ++j)
8045 ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8046 }
8047 SDValue V = CreateLoad(VT, LDBase);
8048 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8049 : DAG.getConstantFP(0.0, DL, VT);
8050 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8051 }
8052 }
8053 }
8054
8055 // If the upper half of a ymm/zmm load is undef then just load the lower half.
8056 if (VT.is256BitVector() || VT.is512BitVector()) {
8057 unsigned HalfNumElems = NumElems / 2;
8058 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
8059 EVT HalfVT =
8060 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8061 SDValue HalfLD =
8062 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8063 DAG, Subtarget, IsAfterLegalize, Depth + 1);
8064 if (HalfLD)
8065 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8066 HalfLD, DAG.getVectorIdxConstant(0, DL));
8067 }
8068 }
8069
8070 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8071 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8072 ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
8073 LoadSizeInBits == 64) &&
8074 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8075 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8076 : MVT::getIntegerVT(LoadSizeInBits);
8077 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8078 // Allow v4f32 on SSE1 only targets.
8079 // FIXME: Add more isel patterns so we can just use VT directly.
8080 if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8081 VecVT = MVT::v4f32;
8082 if (TLI.isTypeLegal(VecVT)) {
8083 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8084 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8085 SDValue ResNode = DAG.getMemIntrinsicNode(
8086 X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8088 for (auto *LD : Loads)
8089 if (LD)
8090 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8091 return DAG.getBitcast(VT, ResNode);
8092 }
8093 }
8094
8095 // BROADCAST - match the smallest possible repetition pattern, load that
8096 // scalar/subvector element and then broadcast to the entire vector.
8097 if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8098 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8099 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8100 unsigned RepeatSize = SubElems * BaseSizeInBits;
8101 unsigned ScalarSize = std::min(RepeatSize, 64u);
8102 if (!Subtarget.hasAVX2() && ScalarSize < 32)
8103 continue;
8104
8105 // Don't attempt a 1:N subvector broadcast - it should be caught by
8106 // combineConcatVectorOps, else will cause infinite loops.
8107 if (RepeatSize > ScalarSize && SubElems == 1)
8108 continue;
8109
8110 bool Match = true;
8111 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8112 for (unsigned i = 0; i != NumElems && Match; ++i) {
8113 if (!LoadMask[i])
8114 continue;
8115 SDValue Elt = peekThroughBitcasts(Elts[i]);
8116 if (RepeatedLoads[i % SubElems].isUndef())
8117 RepeatedLoads[i % SubElems] = Elt;
8118 else
8119 Match &= (RepeatedLoads[i % SubElems] == Elt);
8120 }
8121
8122 // We must have loads at both ends of the repetition.
8123 Match &= !RepeatedLoads.front().isUndef();
8124 Match &= !RepeatedLoads.back().isUndef();
8125 if (!Match)
8126 continue;
8127
8128 EVT RepeatVT =
8129 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8130 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8131 : EVT::getFloatingPointVT(ScalarSize);
8132 if (RepeatSize > ScalarSize)
8133 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8134 RepeatSize / ScalarSize);
8135 EVT BroadcastVT =
8136 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8137 VT.getSizeInBits() / ScalarSize);
8138 if (TLI.isTypeLegal(BroadcastVT)) {
8139 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8140 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize,
8141 Depth + 1)) {
8142 SDValue Broadcast = RepeatLoad;
8143 if (RepeatSize > ScalarSize) {
8144 while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
8145 Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
8146 } else {
8147 if (!Subtarget.hasAVX2() &&
8149 RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
8150 Subtarget,
8151 /*AssumeSingleUse=*/true))
8152 return SDValue();
8153 Broadcast =
8154 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
8155 }
8156 return DAG.getBitcast(VT, Broadcast);
8157 }
8158 }
8159 }
8160 }
8161
8162 // STRIDED - element loads at a uniform byte stride larger than the element
8163 // size are folded into wide load(s) + vector truncation.
8164 // Depth 1 lets the REVERSE block below recurse into us to catch reverse
8165 // strides.
8166 if (Depth <= 1 && Subtarget.hasAVX2() && !IsConsecutiveLoad &&
8167 LoadMask.isAllOnes() && isPowerOf2_32(NumElems) && BaseSizeInBits <= 32 &&
8168 VT.getSizeInBits() >= 128) {
8169 unsigned WideEltBits = 0;
8170 for (unsigned Trial : {16u, 32u, 64u}) {
8171 if (Trial <= BaseSizeInBits || Trial % BaseSizeInBits != 0)
8172 continue;
8173 unsigned LaneStride = Trial / BaseSizeInBits;
8174 bool AllMatch = true;
8175 for (unsigned K = 1; K < NumElems && AllMatch; ++K) {
8176 AllMatch = AllMatch && ByteOffsets[K] == 0 &&
8178 Loads[K], LDBase, BaseSizeInBytes, K * LaneStride);
8179 }
8180 if (AllMatch) {
8181 WideEltBits = Trial;
8182 break;
8183 }
8184 }
8185 if (WideEltBits != 0) {
8186 MVT WideEltVT = MVT::getIntegerVT(WideEltBits);
8187 MVT SrcEltVT = MVT::getIntegerVT(BaseSizeInBits);
8188 // The wide loads read (stride - element) bytes past the last element.
8189 // A stride-aligned base keeps every stride block inside a page that an
8190 // accessed element touches.
8191 unsigned StrideBytes = WideEltBits / 8;
8192 bool RangeSafe =
8193 LDBase->getBaseAlign() >= Align(StrideBytes) ||
8195 NumElems * StrideBytes, *DAG.getContext(), DAG.getDataLayout());
8196 for (unsigned WideRegBits : {512u, 256u, 128u}) {
8197 unsigned LanesPerWideLoad = WideRegBits / WideEltBits;
8198 if (LanesPerWideLoad < 2 || NumElems % LanesPerWideLoad != 0)
8199 continue;
8200 // Truncate to a legal piece at least 128-bit and no narrower
8201 // than the source element.
8202 unsigned PieceEltBits =
8203 std::max(BaseSizeInBits, 128 / LanesPerWideLoad);
8204 MVT PieceEltVT = MVT::getIntegerVT(PieceEltBits);
8205 MVT WideVT = MVT::getVectorVT(WideEltVT, LanesPerWideLoad);
8206 MVT PieceVT = MVT::getVectorVT(PieceEltVT, LanesPerWideLoad);
8207 MVT TruncVT = MVT::getVectorVT(SrcEltVT, NumElems);
8208 MVT ConcatVT = MVT::getVectorVT(PieceEltVT, NumElems);
8209 if (!TLI.isTypeLegal(WideVT) || !TLI.isTypeLegal(PieceVT) ||
8210 !TLI.isTypeLegal(ConcatVT) || !TLI.isTypeLegal(TruncVT))
8211 continue;
8212 unsigned NumWideLoads = NumElems / LanesPerWideLoad;
8213 unsigned BytesPerWideLoad = WideRegBits / 8;
8214 // Without a provable range the last load is shifted back to end at
8215 // the last element. It overlaps the previous load so two are needed.
8216 bool CanShift = NumWideLoads >= 2;
8217 if (!RangeSafe && !CanShift)
8218 continue;
8219 unsigned TailBits = WideEltBits - BaseSizeInBits;
8220 auto MMOFlags = LDBase->getMemOperand()->getFlags();
8221 SDValue BasePtr = LDBase->getBasePtr();
8223 for (unsigned K = 0; K != NumWideLoads; ++K) {
8224 bool ShiftLast = !RangeSafe && K == NumWideLoads - 1;
8225 unsigned Offset = K * BytesPerWideLoad;
8226 if (ShiftLast)
8227 Offset -= TailBits / 8;
8228 SDValue Ptr =
8230 Align LdAlign = commonAlignment(LDBase->getBaseAlign(), Offset);
8231 SDValue Ld =
8232 DAG.getLoad(WideVT, DL, LDBase->getChain(), Ptr,
8234 LdAlign, MMOFlags);
8235 for (auto *LD : Loads)
8236 if (LD)
8237 DAG.makeEquivalentMemoryOrdering(LD, Ld);
8238 // The shifted load leaves each element in its lane's high bits.
8239 if (ShiftLast)
8240 Ld = DAG.getNode(ISD::SRL, DL, WideVT, Ld,
8241 DAG.getShiftAmountConstant(TailBits, WideVT, DL));
8242 Pieces.push_back(DAG.getNode(ISD::TRUNCATE, DL, PieceVT, Ld));
8243 }
8244 SDValue Result = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, Pieces);
8245 Result = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Result);
8246 return DAG.getBitcast(VT, Result);
8247 }
8248 }
8249 }
8250
8251 // REVERSE - attempt to match the loads in reverse and then shuffle back.
8252 // TODO: Do this for any permute or mismatching element counts.
8253 if (Depth == 0 && ZeroMask.isZero() && UndefMask.isZero() &&
8254 TLI.isTypeLegal(VT) && VT.isVector() &&
8255 NumElems == VT.getVectorNumElements()) {
8256 SmallVector<SDValue, 16> ReverseElts(Elts.rbegin(), Elts.rend());
8258 VT, ReverseElts, DL, DAG, Subtarget, IsAfterLegalize, Depth + 1)) {
8259 SmallVector<int, 16> ReverseMask(NumElems);
8260 std::iota(ReverseMask.rbegin(), ReverseMask.rend(), 0);
8261 return DAG.getVectorShuffle(VT, DL, RevLd, DAG.getUNDEF(VT), ReverseMask);
8262 }
8263 }
8264
8265 return SDValue();
8266}
8267
8268// Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8269// load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8270// are consecutive, non-overlapping, and in the right order.
8272 SelectionDAG &DAG,
8273 const X86Subtarget &Subtarget,
8274 bool IsAfterLegalize) {
8276 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8277 if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8278 Elts.push_back(Elt);
8279 continue;
8280 }
8281 return SDValue();
8282 }
8283 assert(Elts.size() == VT.getVectorNumElements());
8284 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8285 IsAfterLegalize);
8286}
8287
8289 const APInt &Undefs, LLVMContext &C) {
8290 unsigned ScalarSize = VT.getScalarSizeInBits();
8291 Type *Ty = EVT(VT.getScalarType()).getTypeForEVT(C);
8292
8293 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8294 if (VT.isFloatingPoint()) {
8295 if (ScalarSize == 16)
8296 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8297 if (ScalarSize == 32)
8298 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8299 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8300 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8301 }
8302 return Constant::getIntegerValue(Ty, Val);
8303 };
8304
8305 SmallVector<Constant *, 32> ConstantVec;
8306 for (unsigned I = 0, E = Bits.size(); I != E; ++I)
8307 ConstantVec.push_back(Undefs[I] ? UndefValue::get(Ty)
8308 : getConstantScalar(Bits[I]));
8309
8310 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8311}
8312
8313static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8314 unsigned SplatBitSize, LLVMContext &C) {
8315 unsigned ScalarSize = VT.getScalarSizeInBits();
8316
8317 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8318 if (VT.isFloatingPoint()) {
8319 if (ScalarSize == 16)
8320 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8321 if (ScalarSize == 32)
8322 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8323 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8324 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8325 }
8326 return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8327 };
8328
8329 if (ScalarSize == SplatBitSize)
8330 return getConstantScalar(SplatValue);
8331
8332 unsigned NumElm = SplatBitSize / ScalarSize;
8333 SmallVector<Constant *, 32> ConstantVec;
8334 for (unsigned I = 0; I != NumElm; ++I) {
8335 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
8336 ConstantVec.push_back(getConstantScalar(Val));
8337 }
8338 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8339}
8340
8342 for (auto *U : N->users()) {
8343 unsigned Opc = U->getOpcode();
8344 // VPERMV/VPERMV3 shuffles can never fold their index operands.
8345 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8346 return false;
8347 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8348 return false;
8349 if (isTargetShuffle(Opc))
8350 return true;
8351 if (Opc == ISD::BITCAST) // Ignore bitcasts
8352 return isFoldableUseOfShuffle(U);
8353 if (N->hasOneUse()) {
8354 // TODO, there may be some general way to know if a SDNode can
8355 // be folded. We now only know whether an MI is foldable.
8356 if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
8357 return false;
8358 return true;
8359 }
8360 }
8361 return false;
8362}
8363
8365 while (V.getOpcode() == ISD::BITCAST ||
8366 V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8367 V = V.getOperand(0);
8368 return isTargetShuffle(V.getOpcode());
8369}
8370
8371// If the node has a single use by a VSELECT then AVX512 targets may be able to
8372// fold as a predicated instruction.
8374 unsigned SizeInBits = V.getValueSizeInBits();
8375 if ((SizeInBits == 512 && Subtarget.hasAVX512()) ||
8376 (SizeInBits >= 128 && Subtarget.hasVLX())) {
8377 if (V.hasOneUse() && V->user_begin()->getOpcode() == ISD::VSELECT &&
8378 V->user_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
8379 return true;
8380 }
8381 }
8382 return false;
8383}
8384
8385/// Attempt to use the vbroadcast instruction to generate a splat value
8386/// from a splat BUILD_VECTOR which uses:
8387/// a. A single scalar load, or a constant.
8388/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8389///
8390/// The VBROADCAST node is returned when a pattern is found,
8391/// or SDValue() otherwise.
8393 const SDLoc &dl,
8394 const X86Subtarget &Subtarget,
8395 SelectionDAG &DAG) {
8396 // VBROADCAST requires AVX.
8397 // TODO: Splats could be generated for non-AVX CPUs using SSE
8398 // instructions, but there's less potential gain for only 128-bit vectors.
8399 if (!Subtarget.hasAVX())
8400 return SDValue();
8401
8402 MVT VT = BVOp->getSimpleValueType(0);
8403 unsigned NumElts = VT.getVectorNumElements();
8405 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8406 "Unsupported vector type for broadcast.");
8407
8408 // See if the build vector is a repeating sequence of scalars (inc. splat).
8409 SDValue Ld;
8410 BitVector UndefElements;
8411 SmallVector<SDValue, 16> Sequence;
8412 if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
8413 assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
8414 if (Sequence.size() == 1)
8415 Ld = Sequence[0];
8416 }
8417
8418 // Attempt to use VBROADCASTM
8419 // From this pattern:
8420 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8421 // b. t1 = (build_vector t0 t0)
8422 //
8423 // Create (VBROADCASTM v2i1 X)
8424 if (!Sequence.empty() && Subtarget.hasCDI()) {
8425 // If not a splat, are the upper sequence values zeroable?
8426 unsigned SeqLen = Sequence.size();
8427 bool UpperZeroOrUndef =
8428 SeqLen == 1 ||
8429 llvm::all_of(ArrayRef(Sequence).drop_front(),
8430 [](SDValue V) { return !V || isNullConstantOrUndef(V); });
8431 SDValue Op0 = Sequence[0];
8432 if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
8433 (Op0.getOpcode() == ISD::ZERO_EXTEND &&
8434 Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
8435 SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
8436 ? Op0.getOperand(0)
8437 : Op0.getOperand(0).getOperand(0);
8438 MVT MaskVT = BOperand.getSimpleValueType();
8439 MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
8440 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8441 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8442 MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
8443 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
8444 unsigned Scale = 512 / VT.getSizeInBits();
8445 BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
8446 }
8447 SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
8448 if (BcstVT.getSizeInBits() != VT.getSizeInBits())
8449 Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
8450 return DAG.getBitcast(VT, Bcst);
8451 }
8452 }
8453 }
8454
8455 unsigned NumUndefElts = UndefElements.count();
8456 if (!Ld || (NumElts - NumUndefElts) <= 1) {
8457 APInt SplatValue, Undef;
8458 unsigned SplatBitSize;
8459 bool HasUndef;
8460 // Check if this is a repeated constant pattern suitable for broadcasting.
8461 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8462 SplatBitSize > VT.getScalarSizeInBits() &&
8463 SplatBitSize < VT.getSizeInBits()) {
8464 // Avoid replacing with broadcast when it's a use of a shuffle
8465 // instruction to preserve the present custom lowering of shuffles.
8466 if (isFoldableUseOfShuffle(BVOp))
8467 return SDValue();
8468 // replace BUILD_VECTOR with broadcast of the repeated constants.
8469 LLVMContext *Ctx = DAG.getContext();
8470 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8471 if (SplatBitSize == 32 || SplatBitSize == 64 ||
8472 (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8473 // Load the constant scalar/subvector and broadcast it.
8474 MVT CVT = MVT::getIntegerVT(SplatBitSize);
8475 Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8476 SDValue CP = DAG.getConstantPool(C, PVT);
8477 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8478
8479 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8480 SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8481 SDValue Ops[] = {DAG.getEntryNode(), CP};
8482 MachinePointerInfo MPI =
8484 SDValue Brdcst =
8485 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8486 MPI, Alignment, MachineMemOperand::MOLoad);
8487 return DAG.getBitcast(VT, Brdcst);
8488 }
8489 if (SplatBitSize > 64) {
8490 // Load the vector of constants and broadcast it.
8491 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8492 SDValue VCP = DAG.getConstantPool(VecC, PVT);
8493 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8494 MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
8495 Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8496 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8497 SDValue Ops[] = {DAG.getEntryNode(), VCP};
8498 MachinePointerInfo MPI =
8500 return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
8501 Ops, VVT, MPI, Alignment,
8503 }
8504 }
8505
8506 // If we are moving a scalar into a vector (Ld must be set and all elements
8507 // but 1 are undef) and that operation is not obviously supported by
8508 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8509 // That's better than general shuffling and may eliminate a load to GPR and
8510 // move from scalar to vector register.
8511 if (!Ld || NumElts - NumUndefElts != 1)
8512 return SDValue();
8513 unsigned ScalarSize = Ld.getValueSizeInBits();
8514 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8515 return SDValue();
8516 }
8517
8518 bool ConstSplatVal =
8519 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8520 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8521
8522 // TODO: Handle broadcasts of non-constant sequences.
8523
8524 // Make sure that all of the users of a non-constant load are from the
8525 // BUILD_VECTOR node.
8526 // FIXME: Is the use count needed for non-constant, non-load case?
8527 if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8528 return SDValue();
8529
8530 unsigned ScalarSize = Ld.getValueSizeInBits();
8531 bool IsGE256 = (VT.getSizeInBits() >= 256);
8532
8533 // When optimizing for size, generate up to 5 extra bytes for a broadcast
8534 // instruction to save 8 or more bytes of constant pool data.
8535 // TODO: If multiple splats are generated to load the same constant,
8536 // it may be detrimental to overall size. There needs to be a way to detect
8537 // that condition to know if this is truly a size win.
8538 bool OptForSize = DAG.shouldOptForSize();
8539
8540 // Handle broadcasting a single constant scalar from the constant pool
8541 // into a vector.
8542 // On Sandybridge (no AVX2), it is still better to load a constant vector
8543 // from the constant pool and not to broadcast it from a scalar.
8544 // But override that restriction when optimizing for size.
8545 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8546 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8547 EVT CVT = Ld.getValueType();
8548 assert(!CVT.isVector() && "Must not broadcast a vector type");
8549
8550 // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
8551 // For size optimization, also splat v2f64 and v2i64, and for size opt
8552 // with AVX2, also splat i8 and i16.
8553 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8554 if (ScalarSize == 32 ||
8555 (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
8556 (CVT == MVT::f16 && Subtarget.hasAVX2()) ||
8557 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8558 const Constant *C = nullptr;
8560 C = CI->getConstantIntValue();
8562 C = CF->getConstantFPValue();
8563
8564 assert(C && "Invalid constant type");
8565
8566 SDValue CP =
8567 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
8568 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8569
8570 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8571 SDValue Ops[] = {DAG.getEntryNode(), CP};
8572 MachinePointerInfo MPI =
8574 return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8575 MPI, Alignment, MachineMemOperand::MOLoad);
8576 }
8577 }
8578
8579 // Handle AVX2 in-register broadcasts.
8580 if (!IsLoad && Subtarget.hasInt256() &&
8581 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8582 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8583
8584 // The scalar source must be a normal load.
8585 if (!IsLoad)
8586 return SDValue();
8587
8588 // Make sure the non-chain result is only used by this build vector.
8589 if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
8590 return SDValue();
8591
8592 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8593 (Subtarget.hasVLX() && ScalarSize == 64)) {
8594 auto *LN = cast<LoadSDNode>(Ld);
8595 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8596 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8597 SDValue BCast =
8598 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8599 LN->getMemoryVT(), LN->getMemOperand());
8600 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8601 return BCast;
8602 }
8603
8604 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8605 // double since there is no vbroadcastsd xmm
8606 if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
8607 (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
8608 auto *LN = cast<LoadSDNode>(Ld);
8609 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8610 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8611 SDValue BCast =
8612 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8613 LN->getMemoryVT(), LN->getMemOperand());
8614 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8615 return BCast;
8616 }
8617
8618 if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
8619 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8620
8621 // Unsupported broadcast.
8622 return SDValue();
8623}
8624
8625/// For an EXTRACT_VECTOR_ELT with a constant index return the real
8626/// underlying vector and index.
8627///
8628/// Modifies \p ExtractedFromVec to the real vector and returns the real
8629/// index.
8630static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
8631 SDValue ExtIdx) {
8632 int Idx = ExtIdx->getAsZExtVal();
8633 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
8634 return Idx;
8635
8636 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
8637 // lowered this:
8638 // (extract_vector_elt (v8f32 %1), Constant<6>)
8639 // to:
8640 // (extract_vector_elt (vector_shuffle<2,u,u,u>
8641 // (extract_subvector (v8f32 %0), Constant<4>),
8642 // undef)
8643 // Constant<0>)
8644 // In this case the vector is the extract_subvector expression and the index
8645 // is 2, as specified by the shuffle.
8646 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
8647 SDValue ShuffleVec = SVOp->getOperand(0);
8648 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
8649 assert(ShuffleVecVT.getVectorElementType() ==
8650 ExtractedFromVec.getSimpleValueType().getVectorElementType());
8651
8652 int ShuffleIdx = SVOp->getMaskElt(Idx);
8653 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
8654 ExtractedFromVec = ShuffleVec;
8655 return ShuffleIdx;
8656 }
8657 return Idx;
8658}
8659
8661 SelectionDAG &DAG) {
8662 MVT VT = Op.getSimpleValueType();
8663
8664 // Skip if insert_vec_elt is not supported.
8666 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
8667 return SDValue();
8668
8669 unsigned NumElems = Op.getNumOperands();
8670 SDValue VecIn1;
8671 SDValue VecIn2;
8672 SmallVector<unsigned, 4> InsertIndices;
8673 SmallVector<int, 8> Mask(NumElems, -1);
8674
8675 for (unsigned i = 0; i != NumElems; ++i) {
8676 unsigned Opc = Op.getOperand(i).getOpcode();
8677
8678 if (Opc == ISD::POISON || Opc == ISD::UNDEF)
8679 continue;
8680
8682 // Quit if more than 1 elements need inserting.
8683 if (InsertIndices.size() > 1)
8684 return SDValue();
8685
8686 InsertIndices.push_back(i);
8687 continue;
8688 }
8689
8690 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
8691 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
8692
8693 // Quit if non-constant index.
8694 if (!isa<ConstantSDNode>(ExtIdx))
8695 return SDValue();
8696 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
8697
8698 // Quit if extracted from vector of different type.
8699 if (ExtractedFromVec.getValueType() != VT)
8700 return SDValue();
8701
8702 if (!VecIn1.getNode())
8703 VecIn1 = ExtractedFromVec;
8704 else if (VecIn1 != ExtractedFromVec) {
8705 if (!VecIn2.getNode())
8706 VecIn2 = ExtractedFromVec;
8707 else if (VecIn2 != ExtractedFromVec)
8708 // Quit if more than 2 vectors to shuffle
8709 return SDValue();
8710 }
8711
8712 if (ExtractedFromVec == VecIn1)
8713 Mask[i] = Idx;
8714 else if (ExtractedFromVec == VecIn2)
8715 Mask[i] = Idx + NumElems;
8716 }
8717
8718 if (!VecIn1.getNode())
8719 return SDValue();
8720
8721 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getPOISON(VT);
8722 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
8723
8724 for (unsigned Idx : InsertIndices)
8725 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8726 DAG.getVectorIdxConstant(Idx, DL));
8727
8728 return NV;
8729}
8730
8731// Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
8733 const X86Subtarget &Subtarget) {
8734 MVT VT = Op.getSimpleValueType();
8735 MVT SVT = Subtarget.hasFP16() ? MVT::f16 : MVT::i16;
8736 MVT IVT = VT.changeVectorElementType(SVT);
8738 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
8739 NewOps.push_back(DAG.getBitcast(SVT, Op.getOperand(I)));
8740 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
8741 return DAG.getBitcast(VT, Res);
8742}
8743
8744// Lower BUILD_VECTOR operation for vXi1 types.
8746 SelectionDAG &DAG,
8747 const X86Subtarget &Subtarget) {
8748
8749 MVT VT = Op.getSimpleValueType();
8750 assert((VT.getVectorElementType() == MVT::i1) &&
8751 "Unexpected type in LowerBUILD_VECTORvXi1!");
8752 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
8753 ISD::isBuildVectorAllOnes(Op.getNode()))
8754 return Op;
8755
8756 uint64_t Undefs = 0;
8757 uint64_t Immediate = 0;
8758 uint64_t NonConstMask = 0;
8759 SmallSet<SDValue, 16> NonConstElts;
8760 bool HasConstElts = false;
8761 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8762 SDValue In = Op.getOperand(idx);
8763 if (In.isUndef()) {
8764 Undefs |= 1ULL << idx;
8765 continue;
8766 }
8767 if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
8768 Immediate |= (InC->getZExtValue() & 0x1) << idx;
8769 HasConstElts = true;
8770 } else {
8771 NonConstMask |= 1ULL << idx;
8772 NonConstElts.insert(In);
8773 }
8774 }
8775
8776 // for single non-const use " (select i1 elt, imm | elt_mask, imm)"
8777 if (NonConstElts.size() == 1) {
8778 // The build_vector allows the scalar element to be larger than the vector
8779 // element type. We need to mask it to use as a condition unless we know
8780 // the upper bits are zero.
8781 // FIXME: Use computeKnownBits instead of checking specific opcode?
8782 SDValue Cond = *NonConstElts.begin();
8783 assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
8784 if (Cond.getOpcode() != ISD::SETCC)
8785 Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
8786 DAG.getConstant(1, dl, MVT::i8));
8787
8788 uint64_t TrueImm = NonConstMask | Immediate;
8789 uint64_t FalseImm = Immediate;
8790
8791 // Perform the select in the scalar domain so we can use cmov.
8792 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8793 uint64_t TrueLo = (unsigned)TrueImm;
8794 uint64_t TrueHi = TrueImm >> 32;
8795 uint64_t FalseLo = (unsigned)FalseImm;
8796 uint64_t FalseHi = FalseImm >> 32;
8797 SDValue Lo = DAG.getSelect(dl, MVT::i32, Cond,
8798 DAG.getConstant(TrueLo, dl, MVT::i32),
8799 DAG.getConstant(FalseLo, dl, MVT::i32));
8800 SDValue Hi = DAG.getSelect(dl, MVT::i32, Cond,
8801 DAG.getConstant(TrueHi, dl, MVT::i32),
8802 DAG.getConstant(FalseHi, dl, MVT::i32));
8803 Lo = DAG.getBitcast(MVT::v32i1, Lo);
8804 Hi = DAG.getBitcast(MVT::v32i1, Hi);
8805 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
8806 } else {
8807 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8808 // Adjust extended value to -1 as it will improve folding.
8809 if ((TrueImm | Undefs) == (~0ULL >> (64 - VT.getSizeInBits())))
8810 TrueImm = ~0ULL >> (64 - ImmVT.getSizeInBits());
8811 SDValue Select =
8812 DAG.getSelect(dl, ImmVT, Cond, DAG.getConstant(TrueImm, dl, ImmVT),
8813 DAG.getConstant(FalseImm, dl, ImmVT));
8814 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8815 Select = DAG.getBitcast(VecVT, Select);
8816 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
8817 DAG.getVectorIdxConstant(0, dl));
8818 }
8819 }
8820
8821 // See if we can cheaply generate a vXi8 vector and convert to vXi1.
8822 MVT OpVT = Op.getOperand(0).getSimpleValueType();
8823 if (OpVT == MVT::i8 && NonConstMask != 0) {
8824 // On pre-BWI targets, we must extend to vXi32 instead.
8825 MVT ByteVT = VT.changeVectorElementType(MVT::i8);
8826 MVT WideSVT = Subtarget.hasBWI() ? MVT::i8 : MVT::i32;
8827 if (ByteVT.getSizeInBits() < 128) {
8828 WideSVT = ByteVT == MVT::v4i8 ? MVT::i32 : MVT::i64;
8829 ByteVT = MVT::v16i8;
8830 }
8831 MVT WideVT = VT.changeVectorElementType(WideSVT);
8832 if (DAG.getTargetLoweringInfo().isTypeLegal(ByteVT) &&
8833 DAG.getTargetLoweringInfo().isTypeLegal(WideVT)) {
8834 SmallVector<SDValue, 16> Elts(Op->op_values());
8835 Elts.append(ByteVT.getVectorNumElements() - Elts.size(),
8836 DAG.getPOISON(OpVT));
8837 SDValue ByteBV = DAG.getBuildVector(ByteVT, dl, Elts);
8838 SDValue WideBV =
8839 getEXTEND_VECTOR_INREG(ISD::ANY_EXTEND, dl, WideVT, ByteBV, DAG);
8840 WideBV = DAG.getNode(ISD::AND, dl, WideVT, WideBV,
8841 DAG.getConstant(1, dl, WideVT));
8842 return DAG.getSetCC(dl, VT, WideBV, DAG.getConstant(0, dl, WideVT),
8843 ISD::SETNE);
8844 }
8845 }
8846
8847 // insert elements one by one
8848 SDValue DstVec;
8849 if (HasConstElts) {
8850 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8851 SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
8852 SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
8853 ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
8854 ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
8855 DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
8856 } else {
8857 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8858 SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
8859 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8860 DstVec = DAG.getBitcast(VecVT, Imm);
8861 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
8862 DAG.getVectorIdxConstant(0, dl));
8863 }
8864 } else
8865 DstVec = DAG.getUNDEF(VT);
8866
8867 for (unsigned Idx = 0, E = Op.getNumOperands(); Idx != E; ++Idx)
8868 if (NonConstMask & (1ULL << Idx))
8869 DstVec = DAG.getInsertVectorElt(dl, DstVec, Op.getOperand(Idx), Idx);
8870
8871 return DstVec;
8872}
8873
8874[[maybe_unused]] static bool isHorizOp(unsigned Opcode) {
8875 switch (Opcode) {
8876 case X86ISD::PACKSS:
8877 case X86ISD::PACKUS:
8878 case X86ISD::FHADD:
8879 case X86ISD::FHSUB:
8880 case X86ISD::HADD:
8881 case X86ISD::HSUB:
8882 case X86ISD::HADDS:
8883 case X86ISD::HSUBS:
8884 return true;
8885 }
8886 return false;
8887}
8888
8889/// Returns true if is possible to fold MUL and an idiom that has already been
8890/// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8891/// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8892/// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8893///
8894/// Prior to calling this function it should be known that there is some
8895/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8896/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8897/// before replacement of such SDNode with ADDSUB operation. Thus the number
8898/// of \p Opnd0 uses is expected to be equal to 2.
8899/// For example, this function may be called for the following IR:
8900/// %AB = fmul fast <2 x double> %A, %B
8901/// %Sub = fsub fast <2 x double> %AB, %C
8902/// %Add = fadd fast <2 x double> %AB, %C
8903/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8904/// <2 x i32> <i32 0, i32 3>
8905/// There is a def for %Addsub here, which potentially can be replaced by
8906/// X86ISD::ADDSUB operation:
8907/// %Addsub = X86ISD::ADDSUB %AB, %C
8908/// and such ADDSUB can further be replaced with FMADDSUB:
8909/// %Addsub = FMADDSUB %A, %B, %C.
8910///
8911/// The main reason why this method is called before the replacement of the
8912/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8913/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8914/// FMADDSUB is.
8916 SDValue &Opnd1, SDValue &Opnd2,
8917 unsigned ExpectedUses,
8918 bool AllowSubAddOrAddSubContract) {
8919 if (Opnd0.getOpcode() != ISD::FMUL ||
8920 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8921 return false;
8922
8923 // FIXME: These checks must match the similar ones in
8924 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8925 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8926 // or MUL + ADDSUB to FMADDSUB.
8927 bool AllowFusion =
8928 (AllowSubAddOrAddSubContract && Opnd0->getFlags().hasAllowContract());
8929 if (!AllowFusion)
8930 return false;
8931
8932 Opnd2 = Opnd1;
8933 Opnd1 = Opnd0.getOperand(1);
8934 Opnd0 = Opnd0.getOperand(0);
8935
8936 return true;
8937}
8938
8940 SelectionDAG &DAG);
8941
8942/// If a BUILD_VECTOR's source elements all apply the same bit operation and
8943/// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8944/// just apply the bit to the vectors.
8945/// NOTE: Its not in our interest to start make a general purpose vectorizer
8946/// from this, but enough scalar bit operations are created from the later
8947/// legalization + scalarization stages to need basic support.
8949 const X86Subtarget &Subtarget,
8950 SelectionDAG &DAG) {
8951 MVT VT = Op->getSimpleValueType(0);
8952 unsigned NumElems = VT.getVectorNumElements();
8953 unsigned ElemSize = VT.getScalarSizeInBits();
8955
8956 // Check that all elements have the same opcode.
8957 // TODO: Should we allow UNDEFS and if so how many?
8958 unsigned Opcode = Op->getOperand(0).getOpcode();
8959 for (unsigned i = 1; i < NumElems; ++i)
8960 if (Opcode != Op->getOperand(i).getOpcode())
8961 return SDValue();
8962
8963 // TODO: We may be able to add support for other Ops (e.g. ADD/SUB).
8964 bool IsShift = false;
8965 switch (Opcode) {
8966 default:
8967 return SDValue();
8968 case ISD::SHL:
8969 case ISD::SRL:
8970 case ISD::SRA:
8971 IsShift = true;
8972 break;
8973 case ISD::AND:
8974 case ISD::XOR:
8975 case ISD::OR:
8976 // Don't do this if the buildvector is a splat - we'd replace one
8977 // constant with an entire vector.
8978 if (Op->getSplatValue())
8979 return SDValue();
8980 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8981 return SDValue();
8982 break;
8983 }
8984
8985 // Collect elements.
8986 bool RHSAllConst = true;
8987 SmallVector<SDValue, 4> LHSElts, RHSElts;
8988 for (SDValue Elt : Op->ops()) {
8989 SDValue LHS = Elt.getOperand(0);
8990 SDValue RHS = Elt.getOperand(1);
8991 RHSAllConst &= isa<ConstantSDNode>(RHS);
8992 LHSElts.push_back(LHS);
8993 RHSElts.push_back(RHS);
8994 }
8995
8996 // Canonicalize shift amounts.
8997 if (IsShift) {
8998 // We expect the canonicalized RHS operand to be the constant.
8999 // TODO: Permit non-constant XOP/AVX2 cases?
9000 if (!RHSAllConst)
9001 return SDValue();
9002
9003 // Extend shift amounts.
9004 for (SDValue &Op1 : RHSElts)
9005 if (Op1.getValueSizeInBits() != ElemSize)
9006 Op1 = DAG.getZExtOrTrunc(Op1, DL, VT.getScalarType());
9007
9008 // Limit to shifts by uniform immediates.
9009 // TODO: Only accept vXi8/vXi64 special cases?
9010 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
9011 if (any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
9012 return SDValue();
9013 }
9014 assert(all_of(llvm::concat<SDValue>(LHSElts, RHSElts),
9015 [ElemSize](SDValue V) {
9016 return V.getValueSizeInBits() == ElemSize;
9017 }) &&
9018 "Element size mismatch");
9019
9020 // To avoid an increase in GPR->FPU instructions, LHS/RHS must be foldable as
9021 // a load or RHS must be constant.
9022 SDValue LHS = EltsFromConsecutiveLoads(VT, LHSElts, DL, DAG, Subtarget,
9023 /*IsAfterLegalize=*/true);
9024 SDValue RHS = EltsFromConsecutiveLoads(VT, RHSElts, DL, DAG, Subtarget,
9025 /*IsAfterLegalize=*/true);
9026 if (!LHS && !RHS && !RHSAllConst)
9027 return SDValue();
9028
9029 if (!LHS)
9030 LHS = DAG.getBuildVector(VT, DL, LHSElts);
9031 if (!RHS)
9032 RHS = DAG.getBuildVector(VT, DL, RHSElts);
9033 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9034
9035 if (!IsShift)
9036 return Res;
9037
9038 // Immediately lower the shift to ensure the constant build vector doesn't
9039 // get converted to a constant pool before the shift is lowered.
9040 return LowerShift(Res, Subtarget, DAG);
9041}
9042
9043static bool isShuffleFoldableLoad(SDValue);
9044
9045/// Attempt to lower a BUILD_VECTOR of scalar values to a shuffle of splats
9046/// representing a blend.
9048 X86Subtarget const &Subtarget,
9049 SelectionDAG &DAG) {
9050 MVT VT = BVOp->getSimpleValueType(0u);
9051
9052 if (VT != MVT::v4f64)
9053 return SDValue();
9054
9055 // Collect unique operands.
9056 auto UniqueOps = SmallSet<SDValue, 16u>();
9057 for (SDValue Op : BVOp->ops()) {
9058 if (isIntOrFPConstant(Op) || Op.isUndef())
9059 return SDValue();
9060 UniqueOps.insert(Op);
9061 }
9062
9063 // Candidate BUILD_VECTOR must have 2 unique operands.
9064 if (UniqueOps.size() != 2u)
9065 return SDValue();
9066
9067 SDValue Op0 = BVOp->getOperand(0u);
9068 UniqueOps.erase(Op0);
9069 SDValue Op1 = *UniqueOps.begin();
9070
9071 if (Subtarget.hasAVX2() || isShuffleFoldableLoad(Op0) ||
9072 isShuffleFoldableLoad(Op1)) {
9073 // Create shuffle mask.
9074 auto const NumElems = VT.getVectorNumElements();
9075 SmallVector<int, 16u> Mask(NumElems);
9076 for (auto I = 0u; I < NumElems; ++I) {
9077 SDValue Op = BVOp->getOperand(I);
9078 Mask[I] = Op == Op0 ? I : I + NumElems;
9079 }
9080 // Create shuffle of splats.
9081 SDValue NewOp0 = DAG.getSplatBuildVector(VT, DL, Op0);
9082 SDValue NewOp1 = DAG.getSplatBuildVector(VT, DL, Op1);
9083 return DAG.getVectorShuffle(VT, DL, NewOp0, NewOp1, Mask);
9084 }
9085
9086 return SDValue();
9087}
9088
9089/// Widen a BUILD_VECTOR if the scalar operands are freely mergeable.
9091 X86Subtarget const &Subtarget,
9092 SelectionDAG &DAG) {
9093 using namespace SDPatternMatch;
9094 MVT VT = BVOp->getSimpleValueType(0);
9095 MVT SVT = VT.getScalarType();
9096 unsigned NumElts = VT.getVectorNumElements();
9097 unsigned EltBits = SVT.getSizeInBits();
9098
9099 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
9100 return SDValue();
9101
9102 unsigned WideBits = 2 * EltBits;
9103 MVT WideSVT = MVT::getIntegerVT(WideBits);
9104 MVT WideVT = MVT::getVectorVT(WideSVT, NumElts / 2);
9105 if (!DAG.getTargetLoweringInfo().isTypeLegal(WideSVT))
9106 return SDValue();
9107
9109 for (unsigned I = 0; I != NumElts; I += 2) {
9110 SDValue Op0 = BVOp->getOperand(I + 0);
9111 SDValue Op1 = BVOp->getOperand(I + 1);
9112
9113 if (Op0.isUndef() && Op1.isUndef()) {
9114 WideOps.push_back(DAG.getUNDEF(WideSVT));
9115 continue;
9116 }
9117
9118 // TODO: Constant repacking?
9119
9120 // Merge scalars that have been split from the same source.
9121 SDValue X, Y;
9122 if (sd_match(Op0, m_Trunc(m_Value(X))) &&
9123 sd_match(Op1, m_Trunc(m_Srl(m_Value(Y), m_SpecificInt(EltBits)))) &&
9125 X.getValueType().bitsGE(WideSVT)) {
9126 if (X.getValueType().bitsGT(WideSVT))
9127 X = DAG.getNode(ISD::TRUNCATE, DL, WideSVT, X);
9128 WideOps.push_back(X);
9129 continue;
9130 }
9131
9132 return SDValue();
9133 }
9134
9135 assert(WideOps.size() == (NumElts / 2) && "Failed to widen build vector");
9136 return DAG.getBitcast(VT, DAG.getBuildVector(WideVT, DL, WideOps));
9137}
9138
9139/// Create a vector constant without a load. SSE/AVX provide the bare minimum
9140/// functionality to do this, so it's all zeros, all ones, or some derivation
9141/// that is cheap to calculate.
9143 SelectionDAG &DAG,
9144 const X86Subtarget &Subtarget) {
9145 MVT VT = Op.getSimpleValueType();
9146
9147 // Vectors containing all zeros can be matched by pxor and xorps.
9148 if (ISD::isBuildVectorAllZeros(Op.getNode()))
9149 return Op;
9150
9151 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9152 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9153 // vpcmpeqd on 256-bit vectors.
9154 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9155 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9156 return Op;
9157
9158 return getOnesVector(VT, DAG, DL);
9159 }
9160
9161 return SDValue();
9162}
9163
9164/// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9165/// from a vector of source values and a vector of extraction indices.
9166/// The vectors might be manipulated to match the type of the permute op.
9167static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9168 const SDLoc &DL, SelectionDAG &DAG,
9169 const X86Subtarget &Subtarget) {
9170 MVT ShuffleVT = VT;
9171 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9172 unsigned NumElts = VT.getVectorNumElements();
9173 unsigned SizeInBits = VT.getSizeInBits();
9174
9175 // Adjust IndicesVec to match VT size.
9176 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9177 "Illegal variable permute mask size");
9178 if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
9179 // Narrow/widen the indices vector to the correct size.
9180 if (IndicesVec.getValueSizeInBits() > SizeInBits)
9181 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9182 NumElts * VT.getScalarSizeInBits());
9183 else if (IndicesVec.getValueSizeInBits() < SizeInBits)
9184 IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
9185 SDLoc(IndicesVec), SizeInBits);
9186 // Zero-extend the index elements within the vector.
9187 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9188 IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
9189 IndicesVT, IndicesVec);
9190 }
9191 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9192
9193 // Handle SrcVec that don't match VT type.
9194 if (SrcVec.getValueSizeInBits() != SizeInBits) {
9195 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9196 // Handle larger SrcVec by treating it as a larger permute.
9197 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9198 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9199 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9200 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9201 Subtarget, DAG, SDLoc(IndicesVec));
9202 SDValue NewSrcVec =
9203 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9204 if (NewSrcVec)
9205 return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
9206 return SDValue();
9207 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9208 // Widen smaller SrcVec to match VT.
9209 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9210 } else
9211 return SDValue();
9212 }
9213
9214 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9215 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9216 EVT SrcVT = Idx.getValueType();
9217 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9218 uint64_t IndexScale = 0;
9219 uint64_t IndexOffset = 0;
9220
9221 // If we're scaling a smaller permute op, then we need to repeat the
9222 // indices, scaling and offsetting them as well.
9223 // e.g. v4i32 -> v16i8 (Scale = 4)
9224 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9225 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9226 for (uint64_t i = 0; i != Scale; ++i) {
9227 IndexScale |= Scale << (i * NumDstBits);
9228 IndexOffset |= i << (i * NumDstBits);
9229 }
9230
9231 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9232 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9233 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9234 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9235 return Idx;
9236 };
9237
9238 unsigned Opcode = 0;
9239 switch (VT.SimpleTy) {
9240 default:
9241 break;
9242 case MVT::v16i8:
9243 if (Subtarget.hasSSSE3())
9244 Opcode = X86ISD::PSHUFB;
9245 break;
9246 case MVT::v8i16:
9247 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9248 Opcode = X86ISD::VPERMV;
9249 else if (Subtarget.hasSSSE3()) {
9250 Opcode = X86ISD::PSHUFB;
9251 ShuffleVT = MVT::v16i8;
9252 }
9253 break;
9254 case MVT::v4f32:
9255 case MVT::v4i32:
9256 if (Subtarget.hasAVX()) {
9257 Opcode = X86ISD::VPERMILPV;
9258 ShuffleVT = MVT::v4f32;
9259 } else if (Subtarget.hasSSSE3()) {
9260 Opcode = X86ISD::PSHUFB;
9261 ShuffleVT = MVT::v16i8;
9262 }
9263 break;
9264 case MVT::v2f64:
9265 case MVT::v2i64:
9266 if (Subtarget.hasAVX()) {
9267 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
9268 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9269 Opcode = X86ISD::VPERMILPV;
9270 ShuffleVT = MVT::v2f64;
9271 } else if (Subtarget.hasSSE41()) {
9272 // SSE41 can compare v2i64 - select between indices 0 and 1.
9273 return DAG.getSelectCC(
9274 DL, IndicesVec,
9275 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
9276 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
9277 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
9279 }
9280 break;
9281 case MVT::v32i8:
9282 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
9283 Opcode = X86ISD::VPERMV;
9284 else if (Subtarget.hasXOP()) {
9285 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
9286 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
9287 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
9288 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
9289 return DAG.getNode(
9291 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
9292 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
9293 } else if (Subtarget.hasAVX()) {
9294 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
9295 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
9296 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
9297 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
9298 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
9300 // Permute Lo and Hi and then select based on index range.
9301 // This works as SHUFB uses bits[3:0] to permute elements and we don't
9302 // care about the bit[7] as its just an index vector.
9303 SDValue Idx = Ops[2];
9304 EVT VT = Idx.getValueType();
9305 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
9306 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
9307 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
9309 };
9310 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
9311 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
9312 PSHUFBBuilder);
9313 }
9314 break;
9315 case MVT::v16i16:
9316 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9317 Opcode = X86ISD::VPERMV;
9318 else if (Subtarget.hasAVX()) {
9319 // Scale to v32i8 and perform as v32i8.
9320 IndicesVec = ScaleIndices(IndicesVec, 2);
9321 return DAG.getBitcast(
9323 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
9324 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
9325 }
9326 break;
9327 case MVT::v8f32:
9328 case MVT::v8i32:
9329 if (Subtarget.hasAVX2())
9330 Opcode = X86ISD::VPERMV;
9331 else if (Subtarget.hasAVX()) {
9332 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
9333 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9334 {0, 1, 2, 3, 0, 1, 2, 3});
9335 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9336 {4, 5, 6, 7, 4, 5, 6, 7});
9337 if (Subtarget.hasXOP())
9338 return DAG.getBitcast(
9339 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
9340 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9341 // Permute Lo and Hi and then select based on index range.
9342 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
9343 SDValue Res = DAG.getSelectCC(
9344 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
9345 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
9346 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
9348 return DAG.getBitcast(VT, Res);
9349 }
9350 break;
9351 case MVT::v4i64:
9352 case MVT::v4f64:
9353 if (Subtarget.hasAVX512()) {
9354 if (!Subtarget.hasVLX()) {
9355 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9356 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9357 SDLoc(SrcVec));
9358 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9359 DAG, SDLoc(IndicesVec));
9360 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9361 DAG, Subtarget);
9362 return extract256BitVector(Res, 0, DAG, DL);
9363 }
9364 Opcode = X86ISD::VPERMV;
9365 } else if (Subtarget.hasAVX()) {
9366 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9367 SDValue LoLo =
9368 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9369 SDValue HiHi =
9370 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9371 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
9372 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9373 if (Subtarget.hasXOP())
9374 return DAG.getBitcast(
9375 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
9376 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9377 // Permute Lo and Hi and then select based on index range.
9378 // This works as VPERMILPD only uses index bit[1] to permute elements.
9379 SDValue Res = DAG.getSelectCC(
9380 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
9381 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
9382 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
9384 return DAG.getBitcast(VT, Res);
9385 }
9386 break;
9387 case MVT::v64i8:
9388 if (Subtarget.hasVBMI())
9389 Opcode = X86ISD::VPERMV;
9390 break;
9391 case MVT::v32i16:
9392 if (Subtarget.hasBWI())
9393 Opcode = X86ISD::VPERMV;
9394 break;
9395 case MVT::v16f32:
9396 case MVT::v16i32:
9397 case MVT::v8f64:
9398 case MVT::v8i64:
9399 if (Subtarget.hasAVX512())
9400 Opcode = X86ISD::VPERMV;
9401 break;
9402 }
9403 if (!Opcode)
9404 return SDValue();
9405
9406 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
9407 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
9408 "Illegal variable permute shuffle type");
9409
9410 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
9411 if (Scale > 1)
9412 IndicesVec = ScaleIndices(IndicesVec, Scale);
9413
9414 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
9415 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
9416
9417 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
9418 SDValue Res = Opcode == X86ISD::VPERMV
9419 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
9420 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
9421 return DAG.getBitcast(VT, Res);
9422}
9423
9424// Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
9425// reasoned to be a permutation of a vector by indices in a non-constant vector.
9426// (build_vector (extract_elt V, (extract_elt I, 0)),
9427// (extract_elt V, (extract_elt I, 1)),
9428// ...
9429// ->
9430// (vpermv I, V)
9431//
9432// TODO: Handle undefs
9433// TODO: Utilize pshufb and zero mask blending to support more efficient
9434// construction of vectors with constant-0 elements.
9435static SDValue
9437 SelectionDAG &DAG,
9438 const X86Subtarget &Subtarget) {
9439 SDValue SrcVec, IndicesVec;
9440
9441 // Check for a match of the permute source vector and permute index elements.
9442 // This is done by checking that the i-th build_vector operand is of the form:
9443 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
9444 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
9445 SDValue Op = peekThroughOneUseFreeze(V.getOperand(Idx));
9446 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9447 return SDValue();
9448
9449 // If this is the first extract encountered in V, set the source vector,
9450 // otherwise verify the extract is from the previously defined source
9451 // vector.
9452 if (!SrcVec)
9453 SrcVec = Op.getOperand(0);
9454 else if (SrcVec != Op.getOperand(0))
9455 return SDValue();
9456 SDValue ExtractedIndex = Op->getOperand(1);
9457 // Peek through extends.
9458 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
9459 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
9460 ExtractedIndex = ExtractedIndex.getOperand(0);
9461 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9462 return SDValue();
9463
9464 // If this is the first extract from the index vector candidate, set the
9465 // indices vector, otherwise verify the extract is from the previously
9466 // defined indices vector.
9467 if (!IndicesVec)
9468 IndicesVec = ExtractedIndex.getOperand(0);
9469 else if (IndicesVec != ExtractedIndex.getOperand(0))
9470 return SDValue();
9471
9472 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
9473 if (!PermIdx || PermIdx->getAPIntValue() != Idx)
9474 return SDValue();
9475 }
9476
9477 MVT VT = V.getSimpleValueType();
9478 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9479}
9480
9481SDValue
9482X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
9483 SDLoc dl(Op);
9484
9485 MVT VT = Op.getSimpleValueType();
9486 MVT EltVT = VT.getVectorElementType();
9487 MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
9488 unsigned NumElems = Op.getNumOperands();
9489
9490 // Generate vectors for predicate vectors.
9491 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
9492 return LowerBUILD_VECTORvXi1(Op, dl, DAG, Subtarget);
9493
9494 if (VT.getVectorElementType() == MVT::bf16 && Subtarget.hasAVX())
9495 return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
9496
9497 if (SDValue VectorCst = materializeVectorConstant(Op, dl, DAG, Subtarget))
9498 return VectorCst;
9499
9500 unsigned EVTBits = EltVT.getSizeInBits();
9501 APInt UndefMask = APInt::getZero(NumElems);
9502 APInt FrozenUndefMask = APInt::getZero(NumElems);
9503 APInt ZeroMask = APInt::getZero(NumElems);
9504 APInt NonZeroMask = APInt::getZero(NumElems);
9505 bool IsAllConstants = true;
9506 bool OneUseFrozenUndefs = true;
9507 SmallSet<SDValue, 8> Values;
9508 unsigned NumConstants = NumElems;
9509 for (unsigned i = 0; i < NumElems; ++i) {
9510 SDValue Elt = Op.getOperand(i);
9511 if (Elt.isUndef()) {
9512 UndefMask.setBit(i);
9513 continue;
9514 }
9515 if (ISD::isFreezeUndef(Elt.getNode())) {
9516 OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
9517 FrozenUndefMask.setBit(i);
9518 continue;
9519 }
9520 Values.insert(Elt);
9521 if (!isIntOrFPConstant(Elt)) {
9522 IsAllConstants = false;
9523 NumConstants--;
9524 }
9525 if (X86::isZeroNode(Elt)) {
9526 ZeroMask.setBit(i);
9527 } else {
9528 NonZeroMask.setBit(i);
9529 }
9530 }
9531
9532 // All undef vector. Return an UNDEF.
9533 if (UndefMask.isAllOnes())
9534 return DAG.getUNDEF(VT);
9535
9536 // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
9537 if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
9538 return DAG.getFreeze(DAG.getUNDEF(VT));
9539
9540 // All undef/freeze(undef)/zero vector. Return a zero vector.
9541 if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
9542 return getZeroVector(VT, Subtarget, DAG, dl);
9543
9544 // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
9545 // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
9546 // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
9547 // and blend the FREEZE-UNDEF operands back in.
9548 // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
9549 if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
9550 NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
9551 SmallVector<int, 16> BlendMask(NumElems, -1);
9552 SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
9553 for (unsigned i = 0; i < NumElems; ++i) {
9554 if (UndefMask[i]) {
9555 BlendMask[i] = -1;
9556 continue;
9557 }
9558 BlendMask[i] = i;
9559 if (!FrozenUndefMask[i])
9560 Elts[i] = Op.getOperand(i);
9561 else
9562 BlendMask[i] += NumElems;
9563 }
9564 SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
9565 SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
9566 SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
9567 return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
9568 }
9569
9570 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9571
9572 // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
9573 // be better off lowering to a smaller build vector and padding with
9574 // undef/zero.
9575 if ((VT.is256BitVector() || VT.is512BitVector()) &&
9577 unsigned UpperElems = NumElems / 2;
9578 APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
9579 unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
9580 if (NumUpperUndefsOrZeros >= UpperElems) {
9581 if (VT.is512BitVector() &&
9582 NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
9583 UpperElems = NumElems - (NumElems / 4);
9584 // If freeze(undef) is in any upper elements, force to zero.
9585 bool UndefUpper = UndefMask.countl_one() >= UpperElems;
9586 MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
9587 SDValue NewBV =
9588 DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
9589 return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
9590 }
9591 }
9592
9593 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, dl, Subtarget, DAG))
9594 return Broadcast;
9595 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, dl, Subtarget, DAG))
9596 return BitOp;
9597 if (SDValue Blend = lowerBuildVectorAsBlend(BV, dl, Subtarget, DAG))
9598 return Blend;
9599 if (SDValue WideBV = widenBuildVector(BV, dl, Subtarget, DAG))
9600 return WideBV;
9601
9602 unsigned NumZero = ZeroMask.popcount();
9603 unsigned NumNonZero = NonZeroMask.popcount();
9604
9605 // If we are inserting one variable into a vector of non-zero constants, try
9606 // to avoid loading each constant element as a scalar. Load the constants as a
9607 // vector and then insert the variable scalar element. If insertion is not
9608 // supported, fall back to a shuffle to get the scalar blended with the
9609 // constants. Insertion into a zero vector is handled as a special-case
9610 // somewhere below here.
9611 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9612 FrozenUndefMask.isZero() &&
9615 // Create an all-constant vector. The variable element in the old
9616 // build vector is replaced by undef in the constant vector. Save the
9617 // variable scalar element and its index for use in the insertelement.
9618 LLVMContext &Context = *DAG.getContext();
9619 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9620 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9621 SDValue VarElt;
9622 SDValue InsIndex;
9623 for (unsigned i = 0; i != NumElems; ++i) {
9624 SDValue Elt = Op.getOperand(i);
9625 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9626 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9627 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9628 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9629 else if (!Elt.isUndef()) {
9630 assert(!VarElt.getNode() && !InsIndex.getNode() &&
9631 "Expected one variable element in this vector");
9632 VarElt = Elt;
9633 InsIndex = DAG.getVectorIdxConstant(i, dl);
9634 }
9635 }
9636 Constant *CV = ConstantVector::get(ConstVecOps);
9637 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9638
9639 // The constants we just created may not be legal (eg, floating point). We
9640 // must lower the vector right here because we can not guarantee that we'll
9641 // legalize it before loading it. This is also why we could not just create
9642 // a new build vector here. If the build vector contains illegal constants,
9643 // it could get split back up into a series of insert elements.
9644 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9645 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9647 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9648 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9649 unsigned InsertC = InsIndex->getAsZExtVal();
9650 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9651 if (InsertC < NumEltsInLow128Bits)
9652 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9653
9654 // There's no good way to insert into the high elements of a >128-bit
9655 // vector, so use shuffles to avoid an extract/insert sequence.
9656 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
9657 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
9658 SmallVector<int, 8> ShuffleMask;
9659 unsigned NumElts = VT.getVectorNumElements();
9660 for (unsigned i = 0; i != NumElts; ++i)
9661 ShuffleMask.push_back(i == InsertC ? NumElts : i);
9662 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9663 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9664 }
9665
9666 // Special case for single non-zero, non-undef, element.
9667 if (NumNonZero == 1) {
9668 unsigned Idx = NonZeroMask.countr_zero();
9669 SDValue Item = Op.getOperand(Idx);
9670
9671 // If we have a constant or non-constant insertion into the low element of
9672 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9673 // the rest of the elements. This will be matched as movd/movq/movss/movsd
9674 // depending on what the source datatype is.
9675 if (Idx == 0) {
9676 if (NumZero == 0)
9677 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9678
9679 if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
9680 EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
9681 (EltVT == MVT::i16 && Subtarget.hasFP16())) {
9682 assert((VT.is128BitVector() || VT.is256BitVector() ||
9683 VT.is512BitVector()) &&
9684 "Expected an SSE value type!");
9685 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9686 // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
9687 // zero vector.
9688 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9689 }
9690
9691 // We can't directly insert an i8 or i16 into a vector, so zero extend
9692 // it to i32 first.
9693 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9694 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9695 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
9696 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9697 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9698 return DAG.getBitcast(VT, Item);
9699 }
9700 }
9701
9702 // Is it a vector logical left shift?
9703 if (NumElems == 2 && Idx == 1 &&
9704 X86::isZeroNode(Op.getOperand(0)) &&
9705 !X86::isZeroNode(Op.getOperand(1))) {
9706 unsigned NumBits = VT.getSizeInBits();
9707 return getVShift(true, VT,
9709 VT, Op.getOperand(1)),
9710 NumBits/2, DAG, *this, dl);
9711 }
9712
9713 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9714 return SDValue();
9715
9716 // Otherwise, if this is a vector with i32 or f32 elements, and the element
9717 // is a non-constant being inserted into an element other than the low one,
9718 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
9719 // movd/movss) to move this into the low element, then shuffle it into
9720 // place.
9721 if (EVTBits == 32) {
9722 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9723 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9724 }
9725 }
9726
9727 // Splat is obviously ok. Let legalizer expand it to a shuffle.
9728 if (Values.size() == 1) {
9729 if (EVTBits == 32) {
9730 // Instead of a shuffle like this:
9731 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9732 // Check if it's possible to issue this instead.
9733 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9734 unsigned Idx = NonZeroMask.countr_zero();
9735 SDValue Item = Op.getOperand(Idx);
9736 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9737 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9738 }
9739 return SDValue();
9740 }
9741
9742 // A vector full of immediates; various special cases are already
9743 // handled, so this is best done with a single constant-pool load.
9744 if (IsAllConstants)
9745 return SDValue();
9746
9747 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, dl, DAG, Subtarget))
9748 return V;
9749
9750 // See if we can use a vector load to get all of the elements.
9751 {
9752 SmallVector<SDValue, 64> Ops(Op->ops().take_front(NumElems));
9753 if (SDValue LD =
9754 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9755 return LD;
9756 }
9757
9758 // If this is a splat of pairs of 32-bit elements, we can use a narrower
9759 // build_vector and broadcast it.
9760 // TODO: We could probably generalize this more.
9761 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9762 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9763 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9764 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9765 // Make sure all the even/odd operands match.
9766 for (unsigned i = 2; i != NumElems; ++i)
9767 if (Ops[i % 2] != Op.getOperand(i))
9768 return false;
9769 return true;
9770 };
9771 if (CanSplat(Op, NumElems, Ops)) {
9772 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9773 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9774 // Create a new build vector and cast to v2i64/v2f64.
9775 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9776 DAG.getBuildVector(NarrowVT, dl, Ops));
9777 // Broadcast from v2i64/v2f64 and cast to final VT.
9778 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
9779 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9780 NewBV));
9781 }
9782 }
9783
9784 // For AVX-length vectors, build the individual 128-bit pieces and use
9785 // shuffles to put them in place.
9786 if (VT.getSizeInBits() > 128) {
9787 MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
9788
9789 // Build both the lower and upper subvector.
9790 SDValue Lower =
9791 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9793 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9794
9795 // Recreate the wider vector with the lower and upper part.
9796 return concatSubVectors(Lower, Upper, DAG, dl);
9797 }
9798
9799 // Let legalizer expand 2-wide build_vectors.
9800 if (EVTBits == 64) {
9801 if (NumNonZero == 1) {
9802 // One half is zero or undef.
9803 unsigned Idx = NonZeroMask.countr_zero();
9804 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9805 Op.getOperand(Idx));
9806 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9807 }
9808 return SDValue();
9809 }
9810
9811 // If element VT is < 32 bits, convert it to inserts into a zero vector.
9812 if (EVTBits == 8 && NumElems == 16)
9813 if (SDValue V = LowerBuildVectorv16i8(Op, dl, NonZeroMask, NumNonZero,
9814 NumZero, DAG, Subtarget))
9815 return V;
9816
9817 if (EltVT == MVT::i16 && NumElems == 8)
9818 if (SDValue V = LowerBuildVectorv8i16(Op, dl, NonZeroMask, NumNonZero,
9819 NumZero, DAG, Subtarget))
9820 return V;
9821
9822 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9823 if (EVTBits == 32 && NumElems == 4)
9824 if (SDValue V = LowerBuildVectorv4x32(Op, dl, DAG, Subtarget))
9825 return V;
9826
9827 // If element VT is == 32 bits, turn it into a number of shuffles.
9828 if (NumElems == 4 && NumZero > 0) {
9829 SmallVector<SDValue, 8> Ops(NumElems);
9830 for (unsigned i = 0; i < 4; ++i) {
9831 bool isZero = !NonZeroMask[i];
9832 if (isZero)
9833 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9834 else
9835 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9836 }
9837
9838 for (unsigned i = 0; i < 2; ++i) {
9839 switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
9840 default: llvm_unreachable("Unexpected NonZero count");
9841 case 0:
9842 Ops[i] = Ops[i*2]; // Must be a zero vector.
9843 break;
9844 case 1:
9845 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9846 break;
9847 case 2:
9848 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9849 break;
9850 case 3:
9851 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9852 break;
9853 }
9854 }
9855
9856 bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
9857 bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
9858 int MaskVec[] = {
9859 Reverse1 ? 1 : 0,
9860 Reverse1 ? 0 : 1,
9861 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9862 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
9863 };
9864 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9865 }
9866
9867 assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9868
9869 // Check for a build vector from mostly shuffle plus few inserting.
9870 if (SDValue Sh = buildFromShuffleMostly(Op, dl, DAG))
9871 return Sh;
9872
9873 // For SSE 4.1, use insertps to put the high elements into the low element.
9874 if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
9876 if (!Op.getOperand(0).isUndef())
9877 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9878 else
9879 Result = DAG.getUNDEF(VT);
9880
9881 for (unsigned i = 1; i < NumElems; ++i) {
9882 if (Op.getOperand(i).isUndef()) continue;
9883 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9884 Op.getOperand(i), DAG.getVectorIdxConstant(i, dl));
9885 }
9886 return Result;
9887 }
9888
9889 // Otherwise, expand into a number of unpckl*, start by extending each of
9890 // our (non-undef) elements to the full vector width with the element in the
9891 // bottom slot of the vector (which generates no code for SSE).
9892 SmallVector<SDValue, 8> Ops(NumElems);
9893 for (unsigned i = 0; i < NumElems; ++i) {
9894 if (!Op.getOperand(i).isUndef())
9895 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9896 else
9897 Ops[i] = DAG.getUNDEF(VT);
9898 }
9899
9900 // Next, we iteratively mix elements, e.g. for v4f32:
9901 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9902 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9903 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
9904 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9905 // Generate scaled UNPCKL shuffle mask.
9906 SmallVector<int, 16> Mask;
9907 for(unsigned i = 0; i != Scale; ++i)
9908 Mask.push_back(i);
9909 for (unsigned i = 0; i != Scale; ++i)
9910 Mask.push_back(NumElems+i);
9911 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9912
9913 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9914 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9915 }
9916 return Ops[0];
9917}
9918
9919// 256-bit AVX can use the vinsertf128 instruction
9920// to create 256-bit vectors from two other 128-bit ones.
9921// TODO: Detect subvector broadcast here instead of DAG combine?
9923 SelectionDAG &DAG,
9924 const X86Subtarget &Subtarget) {
9925 MVT ResVT = Op.getSimpleValueType();
9926 assert((ResVT.is256BitVector() || ResVT.is512BitVector()) &&
9927 "Value type must be 256-/512-bit wide");
9928
9930 unsigned NumSubElems = Ops[0].getSimpleValueType().getVectorNumElements();
9931 unsigned NumOperands = Op.getNumOperands();
9932
9933 unsigned NumFreezeUndef = 0;
9934 unsigned NumZero = 0;
9935 unsigned NumNonZero = 0;
9936 unsigned NonZeros = 0;
9937 SmallSet<SDValue, 4> Undefs;
9938 for (auto [I, SubVec] : enumerate(Ops)) {
9939 if (SubVec.isUndef())
9940 continue;
9941 if (ISD::isFreezeUndef(SubVec.getNode())) {
9942 // If the freeze(undef) has multiple uses then we must fold to zero.
9943 if (SubVec.hasOneUse()) {
9944 ++NumFreezeUndef;
9945 } else {
9946 ++NumZero;
9947 Undefs.insert(SubVec);
9948 }
9949 } else if (ISD::isBuildVectorAllZeros(SubVec.getNode())) {
9950 ++NumZero;
9951 } else {
9952 assert(I < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9953 NonZeros |= 1 << I;
9954 ++NumNonZero;
9955 }
9956 }
9957
9958 // If we have more than 2 non-zeros, build each half separately.
9959 if (NumNonZero > 2) {
9960 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9961 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9962 ArrayRef<SDValue>(Ops).slice(0, NumOperands / 2));
9963 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9964 ArrayRef<SDValue>(Ops).slice(NumOperands / 2));
9965 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9966 }
9967
9968 // Otherwise, build it up through insert_subvectors.
9969 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9970 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
9971 : DAG.getUNDEF(ResVT));
9972
9973 // Replace Undef operands with ZeroVector.
9974 for (SDValue U : Undefs)
9976 U, getZeroVector(U.getSimpleValueType(), Subtarget, DAG, dl));
9977
9978 for (auto [I, SubVec] : enumerate(Ops)) {
9979 if ((NonZeros & (1 << I)) == 0)
9980 continue;
9981
9982 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9983 DAG.getVectorIdxConstant(I * NumSubElems, dl));
9984 }
9985
9986 return Vec;
9987}
9988
9989// Returns true if the given node is a type promotion (by concatenating i1
9990// zeros) of the result of a node that already zeros all upper bits of
9991// k-register.
9992// TODO: Merge this with LowerAVXCONCAT_VECTORS?
9994 const X86Subtarget &Subtarget,
9995 SelectionDAG & DAG) {
9996 MVT ResVT = Op.getSimpleValueType();
9997 unsigned NumOperands = Op.getNumOperands();
9998 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9999 "Unexpected number of operands in CONCAT_VECTORS");
10000
10001 uint64_t Zeros = 0;
10002 uint64_t NonZeros = 0;
10003 for (unsigned i = 0; i != NumOperands; ++i) {
10004 SDValue SubVec = Op.getOperand(i);
10005 if (SubVec.isUndef())
10006 continue;
10007 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10008 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10009 Zeros |= (uint64_t)1 << i;
10010 else
10011 NonZeros |= (uint64_t)1 << i;
10012 }
10013
10014 unsigned NumElems = ResVT.getVectorNumElements();
10015
10016 // If we are inserting non-zero vector and there are zeros in LSBs and undef
10017 // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10018 // insert_subvector will give us two kshifts.
10019 if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10020 Log2_64(NonZeros) != NumOperands - 1) {
10021 unsigned Idx = Log2_64(NonZeros);
10022 SDValue SubVec = Op.getOperand(Idx);
10023 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10024 MVT ShiftVT = widenMaskVectorType(ResVT, Subtarget);
10025 Op = widenSubVector(ShiftVT, SubVec, false, Subtarget, DAG, dl);
10026 Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, Op,
10027 DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10028 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10029 DAG.getVectorIdxConstant(0, dl));
10030 }
10031
10032 // If there are zero or one non-zeros we can handle this very simply.
10033 if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10034 SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10035 if (!NonZeros)
10036 return Vec;
10037 unsigned Idx = Log2_64(NonZeros);
10038 SDValue SubVec = Op.getOperand(Idx);
10039 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10040 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10041 DAG.getVectorIdxConstant(Idx * SubVecNumElts, dl));
10042 }
10043
10044 if (NumOperands > 2) {
10045 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10046 ArrayRef<SDUse> Ops = Op->ops();
10047 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10048 Ops.slice(0, NumOperands / 2));
10049 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10050 Ops.slice(NumOperands / 2));
10051 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10052 }
10053
10054 assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
10055
10056 if (ResVT.getVectorNumElements() >= 16)
10057 return Op; // The operation is legal with KUNPCK
10058
10059 SDValue Vec =
10060 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, DAG.getUNDEF(ResVT),
10061 Op.getOperand(0), DAG.getVectorIdxConstant(0, dl));
10062 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10063 DAG.getVectorIdxConstant(NumElems / 2, dl));
10064}
10065
10067 const X86Subtarget &Subtarget,
10068 SelectionDAG &DAG) {
10069 SDLoc DL(Op);
10070 MVT VT = Op.getSimpleValueType();
10071 if (VT.getVectorElementType() == MVT::i1)
10072 return LowerCONCAT_VECTORSvXi1(Op, DL, Subtarget, DAG);
10073
10074 // AVX can use the vinsertf128 instruction to create 256-bit vectors
10075 // from two other 128-bit ones.
10076 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10077 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10078 (VT.is512BitVector() &&
10079 (Op.getNumOperands() == 2 || Op.getNumOperands() == 4)));
10080 return LowerAVXCONCAT_VECTORS(Op, DL, DAG, Subtarget);
10081}
10082
10083//===----------------------------------------------------------------------===//
10084// Vector shuffle lowering
10085//
10086// This is an experimental code path for lowering vector shuffles on x86. It is
10087// designed to handle arbitrary vector shuffles and blends, gracefully
10088// degrading performance as necessary. It works hard to recognize idiomatic
10089// shuffles and lower them to optimal instruction patterns without leaving
10090// a framework that allows reasonably efficient handling of all vector shuffle
10091// patterns.
10092//===----------------------------------------------------------------------===//
10093
10094/// Checks whether the vector elements referenced by two shuffle masks are
10095/// equivalent.
10096static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
10097 int Idx, int ExpectedIdx) {
10098 assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
10099 ExpectedIdx < MaskSize && "Out of range element index");
10100 if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
10101 return false;
10102
10103 EVT VT = Op.getValueType();
10104 EVT ExpectedVT = ExpectedOp.getValueType();
10105
10106 // Sources must be vectors and match the mask's element count.
10107 if (!VT.isVector() || !ExpectedVT.isVector() ||
10108 (int)VT.getVectorNumElements() != MaskSize ||
10109 (int)ExpectedVT.getVectorNumElements() != MaskSize)
10110 return false;
10111
10112 // Exact match.
10113 if (Idx == ExpectedIdx && Op == ExpectedOp)
10114 return true;
10115
10116 switch (Op.getOpcode()) {
10117 case ISD::BUILD_VECTOR:
10118 // If the values are build vectors, we can look through them to find
10119 // equivalent inputs that make the shuffles equivalent.
10120 return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
10121 case ISD::BITCAST: {
10123 EVT SrcVT = Src.getValueType();
10124 if (Op == ExpectedOp && SrcVT.isVector()) {
10125 if ((SrcVT.getScalarSizeInBits() % VT.getScalarSizeInBits()) == 0) {
10126 unsigned Scale = SrcVT.getScalarSizeInBits() / VT.getScalarSizeInBits();
10127 return (Idx % Scale) == (ExpectedIdx % Scale) &&
10128 IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10129 Idx / Scale, ExpectedIdx / Scale);
10130 }
10131 if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0) {
10132 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
10133 for (unsigned I = 0; I != Scale; ++I)
10134 if (!IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10135 (Idx * Scale) + I,
10136 (ExpectedIdx * Scale) + I))
10137 return false;
10138 return true;
10139 }
10140 }
10141 break;
10142 }
10143 case ISD::VECTOR_SHUFFLE: {
10144 auto *SVN = cast<ShuffleVectorSDNode>(Op);
10145 return Op == ExpectedOp &&
10146 SVN->getMaskElt(Idx) == SVN->getMaskElt(ExpectedIdx);
10147 }
10148 case X86ISD::VBROADCAST:
10149 case X86ISD::VBROADCAST_LOAD:
10150 return Op == ExpectedOp;
10151 case X86ISD::SUBV_BROADCAST_LOAD:
10152 if (Op == ExpectedOp) {
10153 auto *MemOp = cast<MemSDNode>(Op);
10154 unsigned NumMemElts = MemOp->getMemoryVT().getVectorNumElements();
10155 return (Idx % NumMemElts) == (ExpectedIdx % NumMemElts);
10156 }
10157 break;
10158 case X86ISD::VPERMI: {
10159 if (Op == ExpectedOp) {
10161 DecodeVPERMMask(MaskSize, Op.getConstantOperandVal(1), Mask);
10162 SDValue Src = Op.getOperand(0);
10163 return IsElementEquivalent(MaskSize, Src, Src, Mask[Idx],
10164 Mask[ExpectedIdx]);
10165 }
10166 break;
10167 }
10168 case X86ISD::HADD:
10169 case X86ISD::HSUB:
10170 case X86ISD::FHADD:
10171 case X86ISD::FHSUB:
10172 case X86ISD::PACKSS:
10173 case X86ISD::PACKUS:
10174 // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
10175 // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
10176 if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
10177 int NumElts = VT.getVectorNumElements();
10178 int NumLanes = VT.getSizeInBits() / 128;
10179 int NumEltsPerLane = NumElts / NumLanes;
10180 int NumHalfEltsPerLane = NumEltsPerLane / 2;
10181 bool SameLane = (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
10182 bool SameElt =
10183 (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
10184 return SameLane && SameElt;
10185 }
10186 break;
10187 }
10188
10189 return false;
10190}
10191
10192/// Tiny helper function to identify a no-op mask.
10193///
10194/// This is a somewhat boring predicate function. It checks whether the mask
10195/// array input, which is assumed to be a single-input shuffle mask of the kind
10196/// used by the X86 shuffle instructions (not a fully general
10197/// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10198/// in-place shuffle are 'no-op's.
10200 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10201 assert(Mask[i] >= -1 && "Out of bound mask element!");
10202 if (Mask[i] >= 0 && Mask[i] != i)
10203 return false;
10204 }
10205 return true;
10206}
10207
10208/// Test whether there are elements crossing LaneSizeInBits lanes in this
10209/// shuffle mask.
10210///
10211/// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10212/// and we routinely test for these.
10213static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10214 unsigned ScalarSizeInBits,
10215 ArrayRef<int> Mask) {
10216 assert(LaneSizeInBits && ScalarSizeInBits &&
10217 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10218 "Illegal shuffle lane size");
10219 int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10220 int Size = Mask.size();
10221 for (int i = 0; i < Size; ++i)
10222 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10223 return true;
10224 return false;
10225}
10226
10227/// Test whether there are elements crossing 128-bit lanes in this
10228/// shuffle mask.
10230 return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10231}
10232
10233/// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
10234/// from multiple lanes - this is different to isLaneCrossingShuffleMask to
10235/// better support 'repeated mask + lane permute' style shuffles.
10236static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
10237 unsigned ScalarSizeInBits,
10238 ArrayRef<int> Mask) {
10239 assert(LaneSizeInBits && ScalarSizeInBits &&
10240 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10241 "Illegal shuffle lane size");
10242 int NumElts = Mask.size();
10243 int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
10244 int NumLanes = NumElts / NumEltsPerLane;
10245 if (NumLanes > 1) {
10246 for (int i = 0; i != NumLanes; ++i) {
10247 int SrcLane = -1;
10248 for (int j = 0; j != NumEltsPerLane; ++j) {
10249 int M = Mask[(i * NumEltsPerLane) + j];
10250 if (M < 0)
10251 continue;
10252 int Lane = (M % NumElts) / NumEltsPerLane;
10253 if (SrcLane >= 0 && SrcLane != Lane)
10254 return true;
10255 SrcLane = Lane;
10256 }
10257 }
10258 }
10259 return false;
10260}
10261
10262/// Test whether a shuffle mask is equivalent within each sub-lane.
10263///
10264/// This checks a shuffle mask to see if it is performing the same
10265/// lane-relative shuffle in each sub-lane. This trivially implies
10266/// that it is also not lane-crossing. It may however involve a blend from the
10267/// same lane of a second vector.
10268///
10269/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10270/// non-trivial to compute in the face of undef lanes. The representation is
10271/// suitable for use with existing 128-bit shuffles as entries from the second
10272/// vector have been remapped to [LaneSize, 2*LaneSize).
10273static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10274 ArrayRef<int> Mask,
10275 SmallVectorImpl<int> &RepeatedMask) {
10276 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10277 RepeatedMask.assign(LaneSize, -1);
10278 int Size = Mask.size();
10279 for (int i = 0; i < Size; ++i) {
10280 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10281 if (Mask[i] < 0)
10282 continue;
10283 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10284 // This entry crosses lanes, so there is no way to model this shuffle.
10285 return false;
10286
10287 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10288 // Adjust second vector indices to start at LaneSize instead of Size.
10289 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10290 : Mask[i] % LaneSize + LaneSize;
10291 if (RepeatedMask[i % LaneSize] < 0)
10292 // This is the first non-undef entry in this slot of a 128-bit lane.
10293 RepeatedMask[i % LaneSize] = LocalM;
10294 else if (RepeatedMask[i % LaneSize] != LocalM)
10295 // Found a mismatch with the repeated mask.
10296 return false;
10297 }
10298 return true;
10299}
10300
10301/// Test whether a shuffle mask is equivalent within each 128-bit lane.
10302static bool
10304 SmallVectorImpl<int> &RepeatedMask) {
10305 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10306}
10307
10308static bool
10310 SmallVector<int, 32> RepeatedMask;
10311 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10312}
10313
10314/// Test whether a shuffle mask is equivalent within each 256-bit lane.
10315static bool
10317 SmallVectorImpl<int> &RepeatedMask) {
10318 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10319}
10320
10321/// Test whether a target shuffle mask is equivalent within each sub-lane.
10322/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10323static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
10324 unsigned EltSizeInBits,
10325 ArrayRef<int> Mask,
10326 SmallVectorImpl<int> &RepeatedMask) {
10327 int LaneSize = LaneSizeInBits / EltSizeInBits;
10328 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10329 int Size = Mask.size();
10330 for (int i = 0; i < Size; ++i) {
10331 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10332 if (Mask[i] == SM_SentinelUndef)
10333 continue;
10334 if (Mask[i] == SM_SentinelZero) {
10335 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10336 return false;
10337 RepeatedMask[i % LaneSize] = SM_SentinelZero;
10338 continue;
10339 }
10340 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10341 // This entry crosses lanes, so there is no way to model this shuffle.
10342 return false;
10343
10344 // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
10345 // later vector indices to start at multiples of LaneSize instead of Size.
10346 int LaneM = Mask[i] / Size;
10347 int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
10348 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10349 // This is the first non-undef entry in this slot of a 128-bit lane.
10350 RepeatedMask[i % LaneSize] = LocalM;
10351 else if (RepeatedMask[i % LaneSize] != LocalM)
10352 // Found a mismatch with the repeated mask.
10353 return false;
10354 }
10355 return true;
10356}
10357
10358/// Test whether a target shuffle mask is equivalent within each sub-lane.
10359/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10360static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10361 ArrayRef<int> Mask,
10362 SmallVectorImpl<int> &RepeatedMask) {
10363 return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
10364 Mask, RepeatedMask);
10365}
10366
10367/// Checks whether a shuffle mask is equivalent to an explicit list of
10368/// arguments.
10369///
10370/// This is a fast way to test a shuffle mask against a fixed pattern:
10371///
10372/// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
10373///
10374/// It returns true if the mask is exactly as wide as the argument list, and
10375/// each element of the mask is either -1 (signifying undef) or the value given
10376/// in the argument.
10377static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
10378 SDValue V1 = SDValue(),
10379 SDValue V2 = SDValue()) {
10380 int Size = Mask.size();
10381 if (Size != (int)ExpectedMask.size())
10382 return false;
10383
10384 for (int i = 0; i < Size; ++i) {
10385 assert(Mask[i] >= -1 && "Out of bound mask element!");
10386 int MaskIdx = Mask[i];
10387 int ExpectedIdx = ExpectedMask[i];
10388 if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
10389 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10390 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10391 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10392 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10393 if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10394 return false;
10395 }
10396 }
10397 return true;
10398}
10399
10400/// Checks whether a target shuffle mask is equivalent to an explicit pattern.
10401///
10402/// The masks must be exactly the same width.
10403///
10404/// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
10405/// value in ExpectedMask is always accepted. Otherwise the indices must match.
10406///
10407/// SM_SentinelZero is accepted as a valid negative index but must match in
10408/// both, or via a known bits test.
10410 ArrayRef<int> ExpectedMask,
10411 const SelectionDAG &DAG,
10412 SDValue V1 = SDValue(),
10413 SDValue V2 = SDValue()) {
10414 int Size = Mask.size();
10415 if (Size != (int)ExpectedMask.size())
10416 return false;
10417 assert(llvm::all_of(ExpectedMask,
10418 [Size](int M) {
10419 return M == SM_SentinelZero ||
10420 isInRange(M, 0, 2 * Size);
10421 }) &&
10422 "Illegal target shuffle mask");
10423
10424 // Check for out-of-range target shuffle mask indices.
10425 if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
10426 return false;
10427
10428 // Don't use V1/V2 if they're not the same size as the shuffle mask type.
10429 if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
10430 !V1.getValueType().isVector()))
10431 V1 = SDValue();
10432 if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
10433 !V2.getValueType().isVector()))
10434 V2 = SDValue();
10435
10436 APInt ZeroV1 = APInt::getZero(Size);
10437 APInt ZeroV2 = APInt::getZero(Size);
10438
10439 for (int i = 0; i < Size; ++i) {
10440 int MaskIdx = Mask[i];
10441 int ExpectedIdx = ExpectedMask[i];
10442 if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
10443 continue;
10444 // If we failed to match an expected SM_SentinelZero then early out.
10445 if (ExpectedIdx < 0)
10446 return false;
10447 if (MaskIdx == SM_SentinelZero) {
10448 // If we need this expected index to be a zero element, then update the
10449 // relevant zero mask and perform the known bits at the end to minimize
10450 // repeated computes.
10451 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10452 if (ExpectedV &&
10453 Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
10454 int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10455 APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
10456 ZeroMask.setBit(BitIdx);
10457 continue;
10458 }
10459 }
10460 if (MaskIdx >= 0) {
10461 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10462 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10463 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10464 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10465 if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10466 continue;
10467 }
10468 return false;
10469 }
10470 return (ZeroV1.isZero() ||
10471 (DAG.MaskedVectorIsZero(V1, ZeroV1) &&
10472 DAG.isGuaranteedNotToBeUndefOrPoison(V1, ZeroV1))) &&
10473 (ZeroV2.isZero() ||
10474 (DAG.MaskedVectorIsZero(V2, ZeroV2) &&
10475 DAG.isGuaranteedNotToBeUndefOrPoison(V2, ZeroV2)));
10476}
10477
10478// Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
10479// instructions.
10481 const SelectionDAG &DAG) {
10482 if (VT != MVT::v8i32 && VT != MVT::v8f32)
10483 return false;
10484
10485 SmallVector<int, 8> Unpcklwd;
10486 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
10487 /* Unary = */ false);
10488 SmallVector<int, 8> Unpckhwd;
10489 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
10490 /* Unary = */ false);
10491 bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
10492 isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
10493 return IsUnpackwdMask;
10494}
10495
10497 const SelectionDAG &DAG) {
10498 // Create 128-bit vector type based on mask size.
10499 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
10500 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
10501
10502 // We can't assume a canonical shuffle mask, so try the commuted version too.
10503 SmallVector<int, 4> CommutedMask(Mask);
10505
10506 // Match any of unary/binary or low/high.
10507 for (unsigned i = 0; i != 4; ++i) {
10508 SmallVector<int, 16> UnpackMask;
10509 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
10510 if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
10511 isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
10512 return true;
10513 }
10514 return false;
10515}
10516
10517/// Return true if a shuffle mask chooses elements identically in its top and
10518/// bottom halves. For example, any splat mask has the same top and bottom
10519/// halves. If an element is undefined in only one half of the mask, the halves
10520/// are not considered identical.
10522 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
10523 unsigned HalfSize = Mask.size() / 2;
10524 for (unsigned i = 0; i != HalfSize; ++i) {
10525 if (Mask[i] != Mask[i + HalfSize])
10526 return false;
10527 }
10528 return true;
10529}
10530
10531/// Get a 4-lane 8-bit shuffle immediate for a mask.
10532///
10533/// This helper function produces an 8-bit shuffle immediate corresponding to
10534/// the ubiquitous shuffle encoding scheme used in x86 instructions for
10535/// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10536/// example.
10537///
10538/// NB: We rely heavily on "undef" masks preserving the input lane.
10539static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10540 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
10541 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
10542 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
10543 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
10544 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
10545
10546 // If the mask only uses one non-undef element, then fully 'splat' it to
10547 // improve later broadcast matching.
10548 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10549 assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
10550
10551 int FirstElt = Mask[FirstIndex];
10552 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
10553 return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
10554
10555 unsigned Imm = 0;
10556 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10557 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10558 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10559 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10560 return Imm;
10561}
10562
10564 SelectionDAG &DAG) {
10565 return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10566}
10567
10568// Canonicalize SHUFPD mask to improve chances of further folding.
10569// Mask elements are assumed to be -1, 0 or 1 to match the SHUFPD lo/hi pattern.
10570static unsigned getSHUFPDImm(ArrayRef<int> Mask) {
10571 assert((Mask.size() == 2 || Mask.size() == 4 || Mask.size() == 8) &&
10572 "Unexpected SHUFPD mask size");
10573 assert(all_of(Mask, [](int M) { return -1 <= M && M <= 1; }) &&
10574 "Unexpected SHUFPD mask elements");
10575
10576 // If the mask only uses one non-undef element, then fully 'splat' it to
10577 // improve later broadcast matching.
10578 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10579 assert(0 <= FirstIndex && FirstIndex < (int)Mask.size() &&
10580 "All undef shuffle mask");
10581
10582 int FirstElt = Mask[FirstIndex];
10583 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }) &&
10584 count_if(Mask, [FirstElt](int M) { return M == FirstElt; }) > 1) {
10585 unsigned Imm = 0;
10586 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10587 Imm |= FirstElt << I;
10588 return Imm;
10589 }
10590
10591 // Attempt to keep any undef elements in place to improve chances of the
10592 // shuffle becoming a (commutative) blend.
10593 unsigned Imm = 0;
10594 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10595 Imm |= (Mask[I] < 0 ? (I & 1) : Mask[I]) << I;
10596
10597 return Imm;
10598}
10599
10601 SelectionDAG &DAG) {
10602 return DAG.getTargetConstant(getSHUFPDImm(Mask), DL, MVT::i8);
10603}
10604
10605// The Shuffle result is as follow:
10606// 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10607// Each Zeroable's element correspond to a particular Mask's element.
10608// As described in computeZeroableShuffleElements function.
10609//
10610// The function looks for a sub-mask that the nonzero elements are in
10611// increasing order. If such sub-mask exist. The function returns true.
10612static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10613 ArrayRef<int> Mask, const EVT &VectorType,
10614 bool &IsZeroSideLeft) {
10615 int NextElement = -1;
10616 // Check if the Mask's nonzero elements are in increasing order.
10617 for (int i = 0, e = Mask.size(); i < e; i++) {
10618 // Checks if the mask's zeros elements are built from only zeros.
10619 assert(Mask[i] >= -1 && "Out of bound mask element!");
10620 if (Mask[i] < 0)
10621 return false;
10622 if (Zeroable[i])
10623 continue;
10624 // Find the lowest non zero element
10625 if (NextElement < 0) {
10626 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10627 IsZeroSideLeft = NextElement != 0;
10628 }
10629 // Exit if the mask's non zero elements are not in increasing order.
10630 if (NextElement != Mask[i])
10631 return false;
10632 NextElement++;
10633 }
10634 return true;
10635}
10636
10637static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
10639 const X86Subtarget &Subtarget,
10640 unsigned Depth = 0);
10641
10642/// Try to lower a shuffle with a single PSHUFB of V1 or V2.
10644 ArrayRef<int> Mask, SDValue V1,
10645 SDValue V2, const APInt &Zeroable,
10646 const X86Subtarget &Subtarget,
10647 SelectionDAG &DAG) {
10648 int Size = Mask.size();
10649 int LaneSize = 128 / VT.getScalarSizeInBits();
10650 const int NumBytes = VT.getSizeInBits() / 8;
10651 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10652
10653 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
10654 (Subtarget.hasAVX2() && VT.is256BitVector()) ||
10655 (Subtarget.hasBWI() && VT.is512BitVector()));
10656
10657 SmallVector<int, 64> PSHUFBMask(NumBytes, -1);
10658 SDValue V;
10659 for (int i = 0; i < NumBytes; ++i) {
10660 int M = Mask[i / NumEltBytes];
10661 if (M < 0)
10662 continue;
10663
10664 if (Zeroable[i / NumEltBytes]) {
10665 // Sign bit set in i8 mask means zero element.
10666 PSHUFBMask[i] = 0x80;
10667 continue;
10668 }
10669
10670 // We can only use a single input of V1 or V2.
10671 SDValue SrcV = (M >= Size ? V2 : V1);
10672 if (V && V != SrcV)
10673 return SDValue();
10674 V = SrcV;
10675 M %= Size;
10676
10677 // PSHUFB can't cross lanes, ensure this doesn't happen.
10678 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10679 return SDValue();
10680
10681 M = M % LaneSize;
10682 M = M * NumEltBytes + (i % NumEltBytes);
10683 PSHUFBMask[i] = M;
10684 }
10685 assert(V && "Failed to find a source input");
10686
10687 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10688 SDValue R = getConstVector(PSHUFBMask, I8VT, DAG, DL, /*IsMask=*/true);
10689 R = DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V), R);
10690 return DAG.getBitcast(VT, R);
10691}
10692
10693/// Return Mask with the necessary casting or extending
10694/// for \p Mask according to \p MaskVT when lowering masking intrinsics
10695static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10696 const X86Subtarget &Subtarget, SelectionDAG &DAG,
10697 const SDLoc &dl) {
10698 MVT SrcVT = Mask.getSimpleValueType();
10699 assert(SrcVT.isScalarInteger() && "Expected scalar integer mask source!");
10700 assert(MaskVT.bitsLE(SrcVT) && "Unexpected mask size!");
10701 assert(MaskVT.getVectorElementType() == MVT::i1 && "Bool vector expected!");
10702
10703 if (isAllOnesConstant(Mask))
10704 return DAG.getConstant(1, dl, MaskVT);
10705 if (X86::isZeroNode(Mask))
10706 return DAG.getConstant(0, dl, MaskVT);
10707
10708 // Attempt to pre-truncate the mask source (to a minimum of i8).
10709 if (SrcVT.getSizeInBits() > MaskVT.getVectorNumElements()) {
10710 SrcVT = MVT::getIntegerVT(std::max((int)MaskVT.getVectorNumElements(), 8));
10711 Mask = DAG.getNode(ISD::TRUNCATE, dl, SrcVT, Mask);
10712 }
10713
10714 if (SrcVT == MVT::i64 && Subtarget.is32Bit()) {
10715 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
10716 assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
10717 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
10718 SDValue Lo, Hi;
10719 std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
10720 Lo = DAG.getBitcast(MVT::v32i1, Lo);
10721 Hi = DAG.getBitcast(MVT::v32i1, Hi);
10722 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
10723 }
10724
10725 MVT BitcastVT = MVT::getVectorVT(MVT::i1, SrcVT.getSizeInBits());
10726 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
10727 // are extracted by EXTRACT_SUBVECTOR.
10728 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
10729 DAG.getBitcast(BitcastVT, Mask),
10730 DAG.getVectorIdxConstant(0, dl));
10731}
10732
10733// X86 has dedicated shuffle that can be lowered to VEXPAND
10735 SDValue V2, ArrayRef<int> Mask,
10736 const APInt &Zeroable,
10737 const X86Subtarget &Subtarget,
10738 SelectionDAG &DAG) {
10739 bool IsLeftZeroSide = true;
10740 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10741 IsLeftZeroSide))
10742 return SDValue();
10743 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10745 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10746 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10747 unsigned NumElts = VT.getVectorNumElements();
10748 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
10749 "Unexpected number of vector elements");
10750 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10751 Subtarget, DAG, DL);
10752 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10753 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10754 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10755}
10756
10758 unsigned &UnpackOpcode, bool IsUnary,
10759 ArrayRef<int> TargetMask, const SDLoc &DL,
10760 SelectionDAG &DAG,
10761 const X86Subtarget &Subtarget) {
10762 int NumElts = VT.getVectorNumElements();
10763
10764 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10765 for (int i = 0; i != NumElts; i += 2) {
10766 int M1 = TargetMask[i + 0];
10767 int M2 = TargetMask[i + 1];
10768 Undef1 &= (SM_SentinelUndef == M1);
10769 Undef2 &= (SM_SentinelUndef == M2);
10770 Zero1 &= isUndefOrZero(M1);
10771 Zero2 &= isUndefOrZero(M2);
10772 }
10773 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
10774 "Zeroable shuffle detected");
10775
10776 // Attempt to match the target mask against the unpack lo/hi mask patterns.
10777 SmallVector<int, 64> Unpckl, Unpckh;
10778 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10779 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
10780 (IsUnary ? V1 : V2))) {
10781 UnpackOpcode = X86ISD::UNPCKL;
10782 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10783 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10784 return true;
10785 }
10786
10787 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10788 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
10789 (IsUnary ? V1 : V2))) {
10790 UnpackOpcode = X86ISD::UNPCKH;
10791 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10792 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10793 return true;
10794 }
10795
10796 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10797 if (IsUnary && (Zero1 || Zero2)) {
10798 // Don't bother if we can blend instead.
10799 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10800 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10801 return false;
10802
10803 bool MatchLo = true, MatchHi = true;
10804 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10805 int M = TargetMask[i];
10806
10807 // Ignore if the input is known to be zero or the index is undef.
10808 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10809 (M == SM_SentinelUndef))
10810 continue;
10811
10812 MatchLo &= (M == Unpckl[i]);
10813 MatchHi &= (M == Unpckh[i]);
10814 }
10815
10816 if (MatchLo || MatchHi) {
10817 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10818 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10819 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10820 return true;
10821 }
10822 }
10823
10824 // If a binary shuffle, commute and try again.
10825 if (!IsUnary) {
10827 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
10828 UnpackOpcode = X86ISD::UNPCKL;
10829 std::swap(V1, V2);
10830 return true;
10831 }
10832
10834 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
10835 UnpackOpcode = X86ISD::UNPCKH;
10836 std::swap(V1, V2);
10837 return true;
10838 }
10839 }
10840
10841 return false;
10842}
10843
10844// X86 has dedicated unpack instructions that can handle specific blend
10845// operations: UNPCKH and UNPCKL.
10847 SDValue V2, ArrayRef<int> Mask,
10848 SelectionDAG &DAG) {
10849 SmallVector<int, 8> Unpckl;
10850 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10851 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10852 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10853
10854 SmallVector<int, 8> Unpckh;
10855 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10856 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10857 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10858
10859 // Commute and try again.
10861 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10862 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10863
10865 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10866 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10867
10868 return SDValue();
10869}
10870
10871/// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
10872/// followed by unpack 256-bit.
10874 SDValue V2, ArrayRef<int> Mask,
10875 SelectionDAG &DAG) {
10876 SmallVector<int, 32> Unpckl, Unpckh;
10877 createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
10878 createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
10879
10880 unsigned UnpackOpcode;
10881 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10882 UnpackOpcode = X86ISD::UNPCKL;
10883 else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10884 UnpackOpcode = X86ISD::UNPCKH;
10885 else
10886 return SDValue();
10887
10888 // This is a "natural" unpack operation (rather than the 128-bit sectored
10889 // operation implemented by AVX). We need to rearrange 64-bit chunks of the
10890 // input in order to use the x86 instruction.
10891 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
10892 DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
10893 V1 = DAG.getBitcast(VT, V1);
10894 return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
10895}
10896
10897// Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
10898// source into the lower elements and zeroing the upper elements.
10899static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
10900 ArrayRef<int> Mask, const APInt &Zeroable,
10901 const X86Subtarget &Subtarget) {
10902 if (!VT.is512BitVector() && !Subtarget.hasVLX())
10903 return false;
10904
10905 unsigned NumElts = Mask.size();
10906 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10907 unsigned MaxScale = 64 / EltSizeInBits;
10908
10909 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10910 unsigned SrcEltBits = EltSizeInBits * Scale;
10911 if (SrcEltBits < 32 && !Subtarget.hasBWI())
10912 continue;
10913 unsigned NumSrcElts = NumElts / Scale;
10914 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
10915 continue;
10916 unsigned UpperElts = NumElts - NumSrcElts;
10917 if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10918 continue;
10919 SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
10920 SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
10921 DstVT = MVT::getIntegerVT(EltSizeInBits);
10922 if ((NumSrcElts * EltSizeInBits) >= 128) {
10923 // ISD::TRUNCATE
10924 DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
10925 } else {
10926 // X86ISD::VTRUNC
10927 DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
10928 }
10929 return true;
10930 }
10931
10932 return false;
10933}
10934
10935// Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
10936// element padding to the final DstVT.
10937static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
10938 const X86Subtarget &Subtarget,
10939 SelectionDAG &DAG, bool ZeroUppers) {
10940 MVT SrcVT = Src.getSimpleValueType();
10941 MVT DstSVT = DstVT.getScalarType();
10942 unsigned NumDstElts = DstVT.getVectorNumElements();
10943 unsigned NumSrcElts = SrcVT.getVectorNumElements();
10944 unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
10945
10946 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
10947 return SDValue();
10948
10949 // Perform a direct ISD::TRUNCATE if possible.
10950 if (NumSrcElts == NumDstElts)
10951 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
10952
10953 if (NumSrcElts > NumDstElts) {
10954 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10955 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10956 return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
10957 }
10958
10959 if ((NumSrcElts * DstEltSizeInBits) >= 128) {
10960 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10961 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10962 return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10963 DstVT.getSizeInBits());
10964 }
10965
10966 // Non-VLX targets must truncate from a 512-bit type, so we need to
10967 // widen, truncate and then possibly extract the original subvector.
10968 if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
10969 SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
10970 return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
10971 }
10972
10973 // Fallback to a X86ISD::VTRUNC, padding if necessary.
10974 MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
10975 SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
10976 if (DstVT != TruncVT)
10977 Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10978 DstVT.getSizeInBits());
10979 return Trunc;
10980}
10981
10982// Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10983//
10984// An example is the following:
10985//
10986// t0: ch = EntryToken
10987// t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10988// t25: v4i32 = truncate t2
10989// t41: v8i16 = bitcast t25
10990// t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10991// Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10992// t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10993// t18: v2i64 = bitcast t51
10994//
10995// One can just use a single vpmovdw instruction, without avx512vl we need to
10996// use the zmm variant and extract the lower subvector, padding with zeroes.
10997// TODO: Merge with lowerShuffleAsVTRUNC.
10999 SDValue V2, ArrayRef<int> Mask,
11000 const APInt &Zeroable,
11001 const X86Subtarget &Subtarget,
11002 SelectionDAG &DAG) {
11003 assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
11004 if (!Subtarget.hasAVX512())
11005 return SDValue();
11006
11007 unsigned NumElts = VT.getVectorNumElements();
11008 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11009 unsigned MaxScale = 64 / EltSizeInBits;
11010 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11011 unsigned SrcEltBits = EltSizeInBits * Scale;
11012 unsigned NumSrcElts = NumElts / Scale;
11013 unsigned UpperElts = NumElts - NumSrcElts;
11014 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11015 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11016 continue;
11017
11018 // Attempt to find a matching source truncation, but as a fall back VLX
11019 // cases can use the VPMOV directly.
11021 if (Src.getOpcode() == ISD::TRUNCATE &&
11022 Src.getScalarValueSizeInBits() == SrcEltBits) {
11023 Src = Src.getOperand(0);
11024 } else if (Subtarget.hasVLX()) {
11025 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11026 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11027 Src = DAG.getBitcast(SrcVT, Src);
11028 // Don't do this if PACKSS/PACKUS could perform it cheaper.
11029 if (Scale == 2 &&
11030 ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
11031 (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
11032 return SDValue();
11033 } else
11034 return SDValue();
11035
11036 // VPMOVWB is only available with avx512bw.
11037 if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
11038 return SDValue();
11039
11040 bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
11041 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11042 }
11043
11044 return SDValue();
11045}
11046
11047// Attempt to match binary shuffle patterns as a truncate.
11049 SDValue V2, ArrayRef<int> Mask,
11050 const APInt &Zeroable,
11051 const X86Subtarget &Subtarget,
11052 SelectionDAG &DAG) {
11053 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11054 "Unexpected VTRUNC type");
11055 if (!Subtarget.hasAVX512() ||
11056 (VT.is256BitVector() && !Subtarget.useAVX512Regs()))
11057 return SDValue();
11058
11059 unsigned NumElts = VT.getVectorNumElements();
11060 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11061 unsigned MaxScale = 64 / EltSizeInBits;
11062 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11063 // TODO: Support non-BWI VPMOVWB truncations?
11064 unsigned SrcEltBits = EltSizeInBits * Scale;
11065 if (SrcEltBits < 32 && !Subtarget.hasBWI())
11066 continue;
11067
11068 // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
11069 // Bail if the V2 elements are undef.
11070 unsigned NumHalfSrcElts = NumElts / Scale;
11071 unsigned NumSrcElts = 2 * NumHalfSrcElts;
11072 for (unsigned Offset = 0; Offset != Scale; ++Offset) {
11073 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
11074 isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
11075 continue;
11076
11077 // The elements beyond the truncation must be undef/zero.
11078 unsigned UpperElts = NumElts - NumSrcElts;
11079 if (UpperElts > 0 &&
11080 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11081 continue;
11082 bool UndefUppers =
11083 UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
11084
11085 // As we're using both sources then we need to concat them together
11086 // and truncate from the double-sized src.
11087 MVT ConcatVT = VT.getDoubleNumVectorElementsVT();
11088
11089 // For offset truncations, ensure that the concat is cheap.
11090 SDValue Src =
11091 combineConcatVectorOps(DL, ConcatVT, {V1, V2}, DAG, Subtarget);
11092 if (!Src) {
11093 if (Offset)
11094 continue;
11095 Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
11096 }
11097
11098 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11099 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11100 Src = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, SrcVT, Src,
11101 Offset * EltSizeInBits, DAG);
11102 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11103 }
11104 }
11105
11106 return SDValue();
11107}
11108
11109/// Check whether a compaction lowering can be done by dropping even/odd
11110/// elements and compute how many times even/odd elements must be dropped.
11111///
11112/// This handles shuffles which take every Nth element where N is a power of
11113/// two. Example shuffle masks:
11114///
11115/// (even)
11116/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
11117/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11118/// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
11119/// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
11120/// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
11121/// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
11122///
11123/// (odd)
11124/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 14
11125/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
11126///
11127/// Any of these lanes can of course be undef.
11128///
11129/// This routine only supports N <= 3.
11130/// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11131/// for larger N.
11132///
11133/// \returns N above, or the number of times even/odd elements must be dropped
11134/// if there is such a number. Otherwise returns zero.
11135static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
11136 bool IsSingleInput) {
11137 // The modulus for the shuffle vector entries is based on whether this is
11138 // a single input or not.
11139 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11140 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
11141 "We should only be called with masks with a power-of-2 size!");
11142
11143 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11144 int Offset = MatchEven ? 0 : 1;
11145
11146 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11147 // and 2^3 simultaneously. This is because we may have ambiguity with
11148 // partially undef inputs.
11149 bool ViableForN[3] = {true, true, true};
11150
11151 for (int i = 0, e = Mask.size(); i < e; ++i) {
11152 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11153 // want.
11154 if (Mask[i] < 0)
11155 continue;
11156
11157 bool IsAnyViable = false;
11158 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11159 if (ViableForN[j]) {
11160 uint64_t N = j + 1;
11161
11162 // The shuffle mask must be equal to (i * 2^N) % M.
11163 if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
11164 IsAnyViable = true;
11165 else
11166 ViableForN[j] = false;
11167 }
11168 // Early exit if we exhaust the possible powers of two.
11169 if (!IsAnyViable)
11170 break;
11171 }
11172
11173 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11174 if (ViableForN[j])
11175 return j + 1;
11176
11177 // Return 0 as there is no viable power of two.
11178 return 0;
11179}
11180
11181// X86 has dedicated pack instructions that can handle specific truncation
11182// operations: PACKSS and PACKUS.
11183// Checks for compaction shuffle masks if MaxStages > 1.
11184// TODO: Add support for matching multiple PACKSS/PACKUS stages.
11185static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11186 unsigned &PackOpcode, ArrayRef<int> TargetMask,
11187 const SelectionDAG &DAG,
11188 const X86Subtarget &Subtarget,
11189 unsigned MaxStages = 1) {
11190 unsigned NumElts = VT.getVectorNumElements();
11191 unsigned BitSize = VT.getScalarSizeInBits();
11192 assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
11193 "Illegal maximum compaction");
11194
11195 auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11196 unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11197 unsigned NumPackedBits = NumSrcBits - BitSize;
11198 N1 = peekThroughBitcasts(N1);
11199 N2 = peekThroughBitcasts(N2);
11200 unsigned NumBits1 = N1.getScalarValueSizeInBits();
11201 unsigned NumBits2 = N2.getScalarValueSizeInBits();
11202 bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
11203 bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
11204 if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
11205 (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
11206 return false;
11207 if (Subtarget.hasSSE41() || BitSize == 8) {
11208 APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11209 if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
11210 (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
11211 V1 = N1;
11212 V2 = N2;
11213 SrcVT = PackVT;
11214 PackOpcode = X86ISD::PACKUS;
11215 return true;
11216 }
11217 }
11218 bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
11219 bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
11220 if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
11221 DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
11222 (N2.isUndef() || IsZero2 || IsAllOnes2 ||
11223 DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
11224 V1 = N1;
11225 V2 = N2;
11226 SrcVT = PackVT;
11227 PackOpcode = X86ISD::PACKSS;
11228 return true;
11229 }
11230 return false;
11231 };
11232
11233 // Attempt to match against wider and wider compaction patterns.
11234 for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11235 MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11236 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11237
11238 // Try binary shuffle.
11239 SmallVector<int, 32> BinaryMask;
11240 createPackShuffleMask(VT, BinaryMask, false, NumStages);
11241 if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
11242 if (MatchPACK(V1, V2, PackVT))
11243 return true;
11244
11245 // Try unary shuffle.
11246 SmallVector<int, 32> UnaryMask;
11247 createPackShuffleMask(VT, UnaryMask, true, NumStages);
11248 if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
11249 if (MatchPACK(V1, V1, PackVT))
11250 return true;
11251 }
11252
11253 return false;
11254}
11255
11257 SDValue V2, ArrayRef<int> Mask,
11258 const X86Subtarget &Subtarget,
11259 SelectionDAG &DAG) {
11260 MVT PackVT;
11261 unsigned PackOpcode;
11262 unsigned SizeBits = VT.getSizeInBits();
11263 unsigned EltBits = VT.getScalarSizeInBits();
11264 unsigned MaxStages = Log2_32(64 / EltBits);
11265 if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11266 Subtarget, MaxStages))
11267 return SDValue();
11268
11269 unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11270 unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11271
11272 // Don't lower multi-stage packs on AVX512, truncation is better.
11273 if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11274 return SDValue();
11275
11276 // Pack to the largest type possible:
11277 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11278 unsigned MaxPackBits = 16;
11279 if (CurrentEltBits > 16 &&
11280 (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11281 MaxPackBits = 32;
11282
11283 // Repeatedly pack down to the target size.
11284 SDValue Res;
11285 for (unsigned i = 0; i != NumStages; ++i) {
11286 unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11287 unsigned NumSrcElts = SizeBits / SrcEltBits;
11288 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11289 MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11290 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11291 MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11292 Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11293 DAG.getBitcast(SrcVT, V2));
11294 V1 = V2 = Res;
11295 CurrentEltBits /= 2;
11296 }
11297 assert(Res && Res.getValueType() == VT &&
11298 "Failed to lower compaction shuffle");
11299 return Res;
11300}
11301
11302/// Try to emit a bitmask instruction for a shuffle.
11303///
11304/// This handles cases where we can model a blend exactly as a bitmask due to
11305/// one of the inputs being zeroable.
11307 SDValue V2, ArrayRef<int> Mask,
11308 const APInt &Zeroable, SelectionDAG &DAG) {
11309 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11310 APInt Zero = APInt::getZero(EltSizeInBIts);
11311 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11312
11313 SmallVector<APInt, 16> VMaskOps(Mask.size(), Zero);
11314 SDValue V;
11315 for (int I = 0, Size = Mask.size(); I != Size; ++I) {
11316 if (Zeroable[I])
11317 continue;
11318 if (Mask[I] % Size != I)
11319 return SDValue(); // Not a blend.
11320 if (!V)
11321 V = Mask[I] < Size ? V1 : V2;
11322 else if (V != (Mask[I] < Size ? V1 : V2))
11323 return SDValue(); // Can only let one input through the mask.
11324
11325 VMaskOps[I] = AllOnes;
11326 }
11327 if (!V)
11328 return SDValue(); // No non-zeroable elements!
11329
11330 MVT LogicVT = VT.changeTypeToInteger();
11331 SDValue VMask = getConstVector(VMaskOps, LogicVT, DAG, DL);
11332 V = DAG.getBitcast(LogicVT, V);
11333 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11334 return DAG.getBitcast(VT, And);
11335}
11336
11337/// Try to emit a blend instruction for a shuffle using bit math.
11338///
11339/// This is used as a fallback approach when first class blend instructions are
11340/// unavailable. Currently it is only suitable for integer vectors, but could
11341/// be generalized for floating point vectors if desirable.
11343 SDValue V2, ArrayRef<int> Mask,
11344 SelectionDAG &DAG) {
11345 assert(VT.isInteger() && "Only supports integer vector types!");
11346 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11347 APInt Zero = APInt::getZero(EltSizeInBIts);
11348 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11349 SmallVector<APInt, 16> MaskOps;
11350 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11351 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11352 return SDValue(); // Shuffled input!
11353 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11354 }
11355 SDValue V1Mask = getConstVector(MaskOps, VT, DAG, DL);
11356 return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
11357}
11358
11360 SDValue PreservedSrc,
11361 const X86Subtarget &Subtarget,
11362 SelectionDAG &DAG);
11363
11366 const APInt &Zeroable, bool &ForceV1Zero,
11367 bool &ForceV2Zero, uint64_t &BlendMask) {
11368 bool V1IsZeroOrUndef =
11369 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11370 bool V2IsZeroOrUndef =
11372
11373 BlendMask = 0;
11374 ForceV1Zero = false, ForceV2Zero = false;
11375 assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11376
11377 int NumElts = Mask.size();
11378 int NumLanes = VT.getSizeInBits() / 128;
11379 int NumEltsPerLane = NumElts / NumLanes;
11380 assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
11381
11382 // For 32/64-bit elements, if we only reference one input (plus any undefs),
11383 // then ensure the blend mask part for that lane just references that input.
11384 bool ForceWholeLaneMasks =
11385 VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
11386
11387 // Attempt to generate the binary blend mask. If an input is zero then
11388 // we can use any lane.
11389 for (int Lane = 0; Lane != NumLanes; ++Lane) {
11390 // Keep track of the inputs used per lane.
11391 bool LaneV1InUse = false;
11392 bool LaneV2InUse = false;
11393 uint64_t LaneBlendMask = 0;
11394 for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
11395 int Elt = (Lane * NumEltsPerLane) + LaneElt;
11396 int M = Mask[Elt];
11397 if (M == SM_SentinelUndef)
11398 continue;
11399 if (M == Elt || (0 <= M && M < NumElts &&
11400 IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
11401 Mask[Elt] = Elt;
11402 LaneV1InUse = true;
11403 continue;
11404 }
11405 if (M == (Elt + NumElts) ||
11406 (NumElts <= M &&
11407 IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
11408 LaneBlendMask |= 1ull << LaneElt;
11409 Mask[Elt] = Elt + NumElts;
11410 LaneV2InUse = true;
11411 continue;
11412 }
11413 if (Zeroable[Elt]) {
11414 if (V1IsZeroOrUndef) {
11415 ForceV1Zero = true;
11416 Mask[Elt] = Elt;
11417 LaneV1InUse = true;
11418 continue;
11419 }
11420 if (V2IsZeroOrUndef) {
11421 ForceV2Zero = true;
11422 LaneBlendMask |= 1ull << LaneElt;
11423 Mask[Elt] = Elt + NumElts;
11424 LaneV2InUse = true;
11425 continue;
11426 }
11427 }
11428 return false;
11429 }
11430
11431 // If we only used V2 then splat the lane blend mask to avoid any demanded
11432 // elts from V1 in this lane (the V1 equivalent is implicit with a zero
11433 // blend mask bit).
11434 if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
11435 LaneBlendMask = (1ull << NumEltsPerLane) - 1;
11436
11437 BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
11438 }
11439 return true;
11440}
11441
11442/// Try to emit a blend instruction for a shuffle.
11443///
11444/// This doesn't do any checks for the availability of instructions for blending
11445/// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11446/// be matched in the backend with the type given. What it does check for is
11447/// that the shuffle mask is a blend, or convertible into a blend with zero.
11449 SDValue V2, ArrayRef<int> Original,
11450 const APInt &Zeroable,
11451 const X86Subtarget &Subtarget,
11452 SelectionDAG &DAG) {
11453 uint64_t BlendMask = 0;
11454 bool ForceV1Zero = false, ForceV2Zero = false;
11455 SmallVector<int, 64> Mask(Original);
11456 if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11457 BlendMask))
11458 return SDValue();
11459
11460 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11461 if (ForceV1Zero)
11462 V1 = getZeroVector(VT, Subtarget, DAG, DL);
11463 if (ForceV2Zero)
11464 V2 = getZeroVector(VT, Subtarget, DAG, DL);
11465
11466 unsigned NumElts = VT.getVectorNumElements();
11467
11468 switch (VT.SimpleTy) {
11469 case MVT::v4i64:
11470 case MVT::v8i32:
11471 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11472 [[fallthrough]];
11473 case MVT::v4f64:
11474 case MVT::v8f32:
11475 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11476 [[fallthrough]];
11477 case MVT::v2f64:
11478 case MVT::v2i64:
11479 case MVT::v4f32:
11480 case MVT::v4i32:
11481 case MVT::v8i16:
11482 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
11483 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
11484 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11485 case MVT::v16i16: {
11486 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
11487 SmallVector<int, 8> RepeatedMask;
11488 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11489 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
11490 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
11491 BlendMask = 0;
11492 for (int i = 0; i < 8; ++i)
11493 if (RepeatedMask[i] >= 8)
11494 BlendMask |= 1ull << i;
11495 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11496 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11497 }
11498 // Use PBLENDW for lower/upper lanes and then blend lanes.
11499 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
11500 // merge to VSELECT where useful.
11501 uint64_t LoMask = BlendMask & 0xFF;
11502 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
11503 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
11504 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11505 DAG.getTargetConstant(LoMask, DL, MVT::i8));
11506 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11507 DAG.getTargetConstant(HiMask, DL, MVT::i8));
11508 return DAG.getVectorShuffle(
11509 MVT::v16i16, DL, Lo, Hi,
11510 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
11511 }
11512 [[fallthrough]];
11513 }
11514 case MVT::v32i8:
11515 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
11516 [[fallthrough]];
11517 case MVT::v16i8: {
11518 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
11519
11520 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
11521 if (SDValue Masked =
11522 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11523 return Masked;
11524
11525 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
11526 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11527 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11528 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11529 }
11530
11531 // If we have VPTERNLOG, we can use that as a bit blend.
11532 if (Subtarget.hasVLX())
11533 if (SDValue BitBlend =
11534 lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
11535 return BitBlend;
11536
11537 // Scale the blend by the number of bytes per element.
11538 int Scale = VT.getScalarSizeInBits() / 8;
11539
11540 // This form of blend is always done on bytes. Compute the byte vector
11541 // type.
11542 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11543
11544 // x86 allows load folding with blendvb from the 2nd source operand. But
11545 // we are still using LLVM select here (see comment below), so that's V1.
11546 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
11547 // allow that load-folding possibility.
11548 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
11550 std::swap(V1, V2);
11551 }
11552
11553 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
11554 // mix of LLVM's code generator and the x86 backend. We tell the code
11555 // generator that boolean values in the elements of an x86 vector register
11556 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
11557 // mapping a select to operand #1, and 'false' mapping to operand #2. The
11558 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
11559 // of the element (the remaining are ignored) and 0 in that high bit would
11560 // mean operand #1 while 1 in the high bit would mean operand #2. So while
11561 // the LLVM model for boolean values in vector elements gets the relevant
11562 // bit set, it is set backwards and over constrained relative to x86's
11563 // actual model.
11564 SmallVector<SDValue, 32> VSELECTMask;
11565 for (int i = 0, Size = Mask.size(); i < Size; ++i)
11566 for (int j = 0; j < Scale; ++j)
11567 VSELECTMask.push_back(
11568 Mask[i] < 0
11569 ? DAG.getUNDEF(MVT::i8)
11570 : DAG.getSignedConstant(Mask[i] < Size ? -1 : 0, DL, MVT::i8));
11571
11572 V1 = DAG.getBitcast(BlendVT, V1);
11573 V2 = DAG.getBitcast(BlendVT, V2);
11574 return DAG.getBitcast(
11575 VT,
11576 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
11577 V1, V2));
11578 }
11579 case MVT::v16f32:
11580 case MVT::v8f64:
11581 case MVT::v8i64:
11582 case MVT::v16i32:
11583 case MVT::v32i16:
11584 case MVT::v64i8: {
11585 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
11586 bool OptForSize = DAG.shouldOptForSize();
11587 if (!OptForSize) {
11588 if (SDValue Masked =
11589 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11590 return Masked;
11591 }
11592
11593 // Otherwise load an immediate into a GPR, cast to k-register, and use a
11594 // masked move.
11595 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11596 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11597 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11598 }
11599 default:
11600 llvm_unreachable("Not a supported integer vector type!");
11601 }
11602}
11603
11604/// Try to lower as a blend of elements from two inputs followed by
11605/// a single-input permutation.
11606///
11607/// This matches the pattern where we can blend elements from two inputs and
11608/// then reduce the shuffle to a single-input permutation.
11610 SDValue V1, SDValue V2,
11611 ArrayRef<int> Mask,
11612 SelectionDAG &DAG,
11613 bool ImmBlends = false) {
11614 // We build up the blend mask while checking whether a blend is a viable way
11615 // to reduce the shuffle.
11616 SmallVector<int, 32> BlendMask(Mask.size(), -1);
11617 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
11618
11619 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11620 if (Mask[i] < 0)
11621 continue;
11622
11623 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
11624
11625 if (BlendMask[Mask[i] % Size] < 0)
11626 BlendMask[Mask[i] % Size] = Mask[i];
11627 else if (BlendMask[Mask[i] % Size] != Mask[i])
11628 return SDValue(); // Can't blend in the needed input!
11629
11630 PermuteMask[i] = Mask[i] % Size;
11631 }
11632
11633 // If only immediate blends, then bail if the blend mask can't be widened to
11634 // i16.
11635 unsigned EltSize = VT.getScalarSizeInBits();
11636 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11637 return SDValue();
11638
11639 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11640 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11641}
11642
11643/// Try to lower as an unpack of elements from two inputs followed by
11644/// a single-input permutation.
11645///
11646/// This matches the pattern where we can unpack elements from two inputs and
11647/// then reduce the shuffle to a single-input (wider) permutation.
11649 SDValue V1, SDValue V2,
11650 ArrayRef<int> Mask,
11651 SelectionDAG &DAG) {
11652 int NumElts = Mask.size();
11653 int NumLanes = VT.getSizeInBits() / 128;
11654 int NumLaneElts = NumElts / NumLanes;
11655 int NumHalfLaneElts = NumLaneElts / 2;
11656
11657 bool MatchLo = true, MatchHi = true;
11658 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11659
11660 // Determine UNPCKL/UNPCKH type and operand order.
11661 for (int Elt = 0; Elt != NumElts; ++Elt) {
11662 int M = Mask[Elt];
11663 if (M < 0)
11664 continue;
11665
11666 // Normalize the mask value depending on whether it's V1 or V2.
11667 int NormM = M;
11668 SDValue &Op = Ops[Elt & 1];
11669 if (M < NumElts && (Op.isUndef() || Op == V1))
11670 Op = V1;
11671 else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
11672 Op = V2;
11673 NormM -= NumElts;
11674 } else
11675 return SDValue();
11676
11677 bool MatchLoAnyLane = false, MatchHiAnyLane = false;
11678 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11679 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11680 MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
11681 MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
11682 if (MatchLoAnyLane || MatchHiAnyLane) {
11683 assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
11684 "Failed to match UNPCKLO/UNPCKHI");
11685 break;
11686 }
11687 }
11688 MatchLo &= MatchLoAnyLane;
11689 MatchHi &= MatchHiAnyLane;
11690 if (!MatchLo && !MatchHi)
11691 return SDValue();
11692 }
11693 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11694
11695 // Element indices have changed after unpacking. Calculate permute mask
11696 // so that they will be put back to the position as dictated by the
11697 // original shuffle mask indices.
11698 SmallVector<int, 32> PermuteMask(NumElts, -1);
11699 for (int Elt = 0; Elt != NumElts; ++Elt) {
11700 int M = Mask[Elt];
11701 if (M < 0)
11702 continue;
11703 int NormM = M;
11704 if (NumElts <= M)
11705 NormM -= NumElts;
11706 bool IsFirstOp = M < NumElts;
11707 int BaseMaskElt =
11708 NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
11709 if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
11710 PermuteMask[Elt] = BaseMaskElt;
11711 else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
11712 PermuteMask[Elt] = BaseMaskElt + 1;
11713 assert(PermuteMask[Elt] != -1 &&
11714 "Input mask element is defined but failed to assign permute mask");
11715 }
11716
11717 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11718 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11719 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11720}
11721
11722/// Try to lower a shuffle as a permute of the inputs followed by an
11723/// UNPCK instruction.
11724///
11725/// This specifically targets cases where we end up with alternating between
11726/// the two inputs, and so can permute them into something that feeds a single
11727/// UNPCK instruction. Note that this routine only targets integer vectors
11728/// because for floating point vectors we have a generalized SHUFPS lowering
11729/// strategy that handles everything that doesn't *exactly* match an unpack,
11730/// making this clever lowering unnecessary.
11732 SDValue V1, SDValue V2,
11733 ArrayRef<int> Mask,
11734 const X86Subtarget &Subtarget,
11735 SelectionDAG &DAG) {
11736 int Size = Mask.size();
11737 assert(Mask.size() >= 2 && "Single element masks are invalid.");
11738
11739 // This routine only supports 128-bit integer dual input vectors.
11740 if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
11741 return SDValue();
11742
11743 int NumLoInputs =
11744 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
11745 int NumHiInputs =
11746 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
11747
11748 bool UnpackLo = NumLoInputs >= NumHiInputs;
11749
11750 auto TryUnpack = [&](int ScalarSize, int Scale) {
11751 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
11752 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
11753
11754 for (int i = 0; i < Size; ++i) {
11755 if (Mask[i] < 0)
11756 continue;
11757
11758 // Each element of the unpack contains Scale elements from this mask.
11759 int UnpackIdx = i / Scale;
11760
11761 // We only handle the case where V1 feeds the first slots of the unpack.
11762 // We rely on canonicalization to ensure this is the case.
11763 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
11764 return SDValue();
11765
11766 // Setup the mask for this input. The indexing is tricky as we have to
11767 // handle the unpack stride.
11768 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
11769 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
11770 Mask[i] % Size;
11771 }
11772
11773 // If we will have to shuffle both inputs to use the unpack, check whether
11774 // we can just unpack first and shuffle the result. If so, skip this unpack.
11775 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
11776 !isNoopShuffleMask(V2Mask))
11777 return SDValue();
11778
11779 // Shuffle the inputs into place.
11780 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11781 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11782
11783 // Cast the inputs to the type we will use to unpack them.
11784 MVT UnpackVT =
11785 MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
11786 V1 = DAG.getBitcast(UnpackVT, V1);
11787 V2 = DAG.getBitcast(UnpackVT, V2);
11788
11789 // Unpack the inputs and cast the result back to the desired type.
11790 return DAG.getBitcast(
11791 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
11792 UnpackVT, V1, V2));
11793 };
11794
11795 // We try each unpack from the largest to the smallest to try and find one
11796 // that fits this mask.
11797 int OrigScalarSize = VT.getScalarSizeInBits();
11798 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
11799 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
11800 return Unpack;
11801
11802 // If we're shuffling with a zero vector then we're better off not doing
11803 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
11804 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
11806 return SDValue();
11807
11808 // If none of the unpack-rooted lowerings worked (or were profitable) try an
11809 // initial unpack.
11810 if (NumLoInputs == 0 || NumHiInputs == 0) {
11811 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
11812 "We have to have *some* inputs!");
11813 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
11814
11815 // FIXME: We could consider the total complexity of the permute of each
11816 // possible unpacking. Or at the least we should consider how many
11817 // half-crossings are created.
11818 // FIXME: We could consider commuting the unpacks.
11819
11820 SmallVector<int, 32> PermMask((unsigned)Size, -1);
11821 for (int i = 0; i < Size; ++i) {
11822 if (Mask[i] < 0)
11823 continue;
11824
11825 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
11826
11827 PermMask[i] =
11828 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
11829 }
11830 return DAG.getVectorShuffle(
11831 VT, DL,
11832 DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
11833 V1, V2),
11834 DAG.getUNDEF(VT), PermMask);
11835 }
11836
11837 return SDValue();
11838}
11839
11840/// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11841/// permuting the elements of the result in place.
11843 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11844 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11845 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11846 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11847 (VT.is512BitVector() && !Subtarget.hasBWI()))
11848 return SDValue();
11849
11850 // We don't currently support lane crossing permutes.
11851 if (is128BitLaneCrossingShuffleMask(VT, Mask))
11852 return SDValue();
11853
11854 int Scale = VT.getScalarSizeInBits() / 8;
11855 int NumLanes = VT.getSizeInBits() / 128;
11856 int NumElts = VT.getVectorNumElements();
11857 int NumEltsPerLane = NumElts / NumLanes;
11858
11859 // Determine range of mask elts.
11860 bool Blend1 = true;
11861 bool Blend2 = true;
11862 std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11863 std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11864 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11865 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11866 int M = Mask[Lane + Elt];
11867 if (M < 0)
11868 continue;
11869 if (M < NumElts) {
11870 Blend1 &= (M == (Lane + Elt));
11871 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11872 M = M % NumEltsPerLane;
11873 Range1.first = std::min(Range1.first, M);
11874 Range1.second = std::max(Range1.second, M);
11875 } else {
11876 M -= NumElts;
11877 Blend2 &= (M == (Lane + Elt));
11878 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11879 M = M % NumEltsPerLane;
11880 Range2.first = std::min(Range2.first, M);
11881 Range2.second = std::max(Range2.second, M);
11882 }
11883 }
11884 }
11885
11886 // Bail if we don't need both elements.
11887 // TODO - it might be worth doing this for unary shuffles if the permute
11888 // can be widened.
11889 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11890 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11891 return SDValue();
11892
11893 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11894 return SDValue();
11895
11896 // Rotate the 2 ops so we can access both ranges, then permute the result.
11897 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11898 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11899 SDValue Rotate = DAG.getBitcast(
11900 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11901 DAG.getBitcast(ByteVT, Lo),
11902 DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11903 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11904 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11905 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11906 int M = Mask[Lane + Elt];
11907 if (M < 0)
11908 continue;
11909 if (M < NumElts)
11910 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11911 else
11912 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
11913 }
11914 }
11915 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
11916 };
11917
11918 // Check if the ranges are small enough to rotate from either direction.
11919 if (Range2.second < Range1.first)
11920 return RotateAndPermute(V1, V2, Range1.first, 0);
11921 if (Range1.second < Range2.first)
11922 return RotateAndPermute(V2, V1, Range2.first, NumElts);
11923 return SDValue();
11924}
11925
11927 return isUndefOrEqual(Mask, 0);
11928}
11929
11931 return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
11932}
11933
11934/// Check if the Mask consists of the same element repeated multiple times.
11936 size_t NumUndefs = 0;
11937 std::optional<int> UniqueElt;
11938 for (int Elt : Mask) {
11939 if (Elt == SM_SentinelUndef) {
11940 NumUndefs++;
11941 continue;
11942 }
11943 if (UniqueElt.has_value() && UniqueElt.value() != Elt)
11944 return false;
11945 UniqueElt = Elt;
11946 }
11947 // Make sure the element is repeated enough times by checking the number of
11948 // undefs is small.
11949 return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
11950}
11951
11952/// Generic routine to decompose a shuffle and blend into independent
11953/// blends and permutes.
11954///
11955/// This matches the extremely common pattern for handling combined
11956/// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11957/// operations. It will try to pick the best arrangement of shuffles and
11958/// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
11960 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11961 const APInt &Zeroable, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11962 int NumElts = Mask.size();
11963 int NumLanes = VT.getSizeInBits() / 128;
11964 int NumEltsPerLane = NumElts / NumLanes;
11965 int EltSizeInBits = VT.getScalarSizeInBits();
11966
11967 // Shuffle the input elements into the desired positions in V1 and V2 and
11968 // unpack/blend them together.
11969 bool IsAlternating = true;
11970 bool V1Zero = true, V2Zero = true;
11971 SmallVector<int, 32> V1Mask(NumElts, -1);
11972 SmallVector<int, 32> V2Mask(NumElts, -1);
11973 SmallVector<int, 32> FinalMask(NumElts, -1);
11974 for (int i = 0; i < NumElts; ++i) {
11975 int M = Mask[i];
11976 if (M >= 0 && M < NumElts) {
11977 V1Mask[i] = M;
11978 FinalMask[i] = i;
11979 V1Zero &= Zeroable[i];
11980 IsAlternating &= (i & 1) == 0;
11981 } else if (M >= NumElts) {
11982 V2Mask[i] = M - NumElts;
11983 FinalMask[i] = i + NumElts;
11984 V2Zero &= Zeroable[i];
11985 IsAlternating &= (i & 1) == 1;
11986 }
11987 }
11988
11989 // If we effectively only demand the 0'th element of \p Input, and not only
11990 // as 0'th element, then broadcast said input,
11991 // and change \p InputMask to be a no-op (identity) mask.
11992 auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
11993 &DAG](SDValue &Input,
11994 MutableArrayRef<int> InputMask) {
11995 unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
11996 if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
11998 return;
11999 if (isNoopShuffleMask(InputMask))
12000 return;
12001 assert(isBroadcastShuffleMask(InputMask) &&
12002 "Expected to demand only the 0'th element.");
12003 Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
12004 for (auto I : enumerate(InputMask)) {
12005 int &InputMaskElt = I.value();
12006 if (InputMaskElt >= 0)
12007 InputMaskElt = I.index();
12008 }
12009 };
12010
12011 // Currently, we may need to produce one shuffle per input, and blend results.
12012 // It is possible that the shuffle for one of the inputs is already a no-op.
12013 // See if we can simplify non-no-op shuffles into broadcasts,
12014 // which we consider to be strictly better than an arbitrary shuffle.
12015 if (isNoopOrBroadcastShuffleMask(V1Mask) &&
12017 canonicalizeBroadcastableInput(V1, V1Mask);
12018 canonicalizeBroadcastableInput(V2, V2Mask);
12019 }
12020
12021 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12022 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12023 // the shuffle may be able to fold with a load or other benefit. However, when
12024 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12025 // pre-shuffle first is a better strategy.
12026 bool V1Noop = isNoopShuffleMask(V1Mask);
12027 bool V2Noop = isNoopShuffleMask(V2Mask);
12028 if (!V1Noop && !V2Noop) {
12029 // If we don't have blends, see if we can create a cheap unpack.
12030 if (!Subtarget.hasSSE41() && VT.is128BitVector() &&
12031 (is128BitUnpackShuffleMask(V1Mask, DAG) ||
12032 is128BitUnpackShuffleMask(V2Mask, DAG)))
12033 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12034 DL, VT, V1, V2, Mask, Subtarget, DAG))
12035 return PermUnpack;
12036
12037 // Only prefer immediate blends to unpack/rotate.
12038 if (SDValue BlendPerm =
12039 lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG, true))
12040 return BlendPerm;
12041
12042 // If either input vector provides only a single element which is repeated
12043 // multiple times, unpacking from both input vectors would generate worse
12044 // code. e.g. for
12045 // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
12046 // it is better to process t4 first to create a vector of t4[0], then unpack
12047 // that vector with t2.
12048 if (!V1Zero && !V2Zero && !isSingleElementRepeatedMask(V1Mask) &&
12050 if (SDValue UnpackPerm =
12051 lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
12052 return UnpackPerm;
12053
12055 DL, VT, V1, V2, Mask, Subtarget, DAG))
12056 return RotatePerm;
12057
12058 // Unpack/rotate failed - try again with variable blends.
12059 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12060 DAG))
12061 return BlendPerm;
12062
12063 if (EltSizeInBits >= 32)
12064 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12065 DL, VT, V1, V2, Mask, Subtarget, DAG))
12066 return PermUnpack;
12067 }
12068
12069 // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12070 // UNPCKL(SHUFFLE, SHUFFLE) pattern unless BLENDI is cheap.
12071 // TODO: It doesn't have to be alternating - but each lane mustn't have more
12072 // than half the elements coming from each source.
12073 bool PreferBlend = EltSizeInBits == 16 && (V1Noop || V2Noop) &&
12074 Subtarget.hasSSE41() &&
12075 is128BitLaneRepeatedShuffleMask(VT, FinalMask);
12076 if (!PreferBlend && IsAlternating && EltSizeInBits < 32) {
12077 V1Mask.assign(NumElts, -1);
12078 V2Mask.assign(NumElts, -1);
12079 FinalMask.assign(NumElts, -1);
12080 for (int i = 0; i != NumElts; i += NumEltsPerLane)
12081 for (int j = 0; j != NumEltsPerLane; ++j) {
12082 int M = Mask[i + j];
12083 if (M >= 0 && M < NumElts) {
12084 V1Mask[i + (j / 2)] = M;
12085 FinalMask[i + j] = i + (j / 2);
12086 } else if (M >= NumElts) {
12087 V2Mask[i + (j / 2)] = M - NumElts;
12088 FinalMask[i + j] = i + (j / 2) + NumElts;
12089 }
12090 }
12091 }
12092
12093 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12094 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12095 return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12096}
12097
12098static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12099 const X86Subtarget &Subtarget,
12100 ArrayRef<int> Mask) {
12101 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12102 assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12103
12104 // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12105 int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12106 int MaxSubElts = 64 / EltSizeInBits;
12107 unsigned RotateAmt, NumSubElts;
12108 if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, MinSubElts,
12109 MaxSubElts, NumSubElts, RotateAmt))
12110 return -1;
12111 unsigned NumElts = Mask.size();
12112 MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12113 RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12114 return RotateAmt;
12115}
12116
12117/// Lower shuffle using X86ISD::VROTLI rotations.
12119 ArrayRef<int> Mask,
12120 const X86Subtarget &Subtarget,
12121 SelectionDAG &DAG) {
12122 // Only XOP + AVX512 targets have bit rotation instructions.
12123 // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12124 bool IsLegal =
12125 (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12126 if (!IsLegal && Subtarget.hasSSE3())
12127 return SDValue();
12128
12129 MVT RotateVT;
12130 int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12131 Subtarget, Mask);
12132 if (RotateAmt < 0)
12133 return SDValue();
12134
12135 // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12136 // expanded to OR(SRL,SHL), will be more efficient, but if they can
12137 // widen to vXi16 or more then existing lowering should will be better.
12138 if (!IsLegal) {
12139 if ((RotateAmt % 16) == 0)
12140 return SDValue();
12141 unsigned ShlAmt = RotateAmt;
12142 unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12143 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, RotateVT, V1,
12144 ShlAmt, DAG);
12145 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, RotateVT, V1,
12146 SrlAmt, DAG);
12147 SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12148 return DAG.getBitcast(VT, Rot);
12149 }
12150
12151 SDValue Rot =
12152 DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12153 DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12154 return DAG.getBitcast(VT, Rot);
12155}
12156
12157/// Try to match a vector shuffle as an element rotation.
12158///
12159/// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
12161 ArrayRef<int> Mask) {
12162 int NumElts = Mask.size();
12163
12164 // We need to detect various ways of spelling a rotation:
12165 // [11, 12, 13, 14, 15, 0, 1, 2]
12166 // [-1, 12, 13, 14, -1, -1, 1, -1]
12167 // [-1, -1, -1, -1, -1, -1, 1, 2]
12168 // [ 3, 4, 5, 6, 7, 8, 9, 10]
12169 // [-1, 4, 5, 6, -1, -1, 9, -1]
12170 // [-1, 4, 5, 6, -1, -1, -1, -1]
12171 int Rotation = 0;
12172 SDValue Lo, Hi;
12173 for (int i = 0; i < NumElts; ++i) {
12174 int M = Mask[i];
12175 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
12176 "Unexpected mask index.");
12177 if (M < 0)
12178 continue;
12179
12180 // Determine where a rotated vector would have started.
12181 int StartIdx = i - (M % NumElts);
12182 if (StartIdx == 0)
12183 // The identity rotation isn't interesting, stop.
12184 return -1;
12185
12186 // If we found the tail of a vector the rotation must be the missing
12187 // front. If we found the head of a vector, it must be how much of the
12188 // head.
12189 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12190
12191 if (Rotation == 0)
12192 Rotation = CandidateRotation;
12193 else if (Rotation != CandidateRotation)
12194 // The rotations don't match, so we can't match this mask.
12195 return -1;
12196
12197 // Compute which value this mask is pointing at.
12198 SDValue MaskV = M < NumElts ? V1 : V2;
12199
12200 // Compute which of the two target values this index should be assigned
12201 // to. This reflects whether the high elements are remaining or the low
12202 // elements are remaining.
12203 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12204
12205 // Either set up this value if we've not encountered it before, or check
12206 // that it remains consistent.
12207 if (!TargetV)
12208 TargetV = MaskV;
12209 else if (TargetV != MaskV)
12210 // This may be a rotation, but it pulls from the inputs in some
12211 // unsupported interleaving.
12212 return -1;
12213 }
12214
12215 // Check that we successfully analyzed the mask, and normalize the results.
12216 assert(Rotation != 0 && "Failed to locate a viable rotation!");
12217 assert((Lo || Hi) && "Failed to find a rotated input vector!");
12218 if (!Lo)
12219 Lo = Hi;
12220 else if (!Hi)
12221 Hi = Lo;
12222
12223 V1 = Lo;
12224 V2 = Hi;
12225
12226 return Rotation;
12227}
12228
12229/// Try to lower a vector shuffle as a byte rotation.
12230///
12231/// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12232/// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12233/// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12234/// try to generically lower a vector shuffle through such an pattern. It
12235/// does not check for the profitability of lowering either as PALIGNR or
12236/// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12237/// This matches shuffle vectors that look like:
12238///
12239/// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12240///
12241/// Essentially it concatenates V1 and V2, shifts right by some number of
12242/// elements, and takes the low elements as the result. Note that while this is
12243/// specified as a *right shift* because x86 is little-endian, it is a *left
12244/// rotate* of the vector lanes.
12246 ArrayRef<int> Mask) {
12247 // Don't accept any shuffles with zero elements.
12248 if (isAnyZero(Mask))
12249 return -1;
12250
12251 // PALIGNR works on 128-bit lanes.
12252 SmallVector<int, 16> RepeatedMask;
12253 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12254 return -1;
12255
12256 int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12257 if (Rotation <= 0)
12258 return -1;
12259
12260 // PALIGNR rotates bytes, so we need to scale the
12261 // rotation based on how many bytes are in the vector lane.
12262 int NumElts = RepeatedMask.size();
12263 int Scale = 16 / NumElts;
12264 return Rotation * Scale;
12265}
12266
12268 SDValue V2, ArrayRef<int> Mask,
12269 const X86Subtarget &Subtarget,
12270 SelectionDAG &DAG) {
12271 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12272
12273 SDValue Lo = V1, Hi = V2;
12274 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12275 if (ByteRotation <= 0)
12276 return SDValue();
12277
12278 // Cast the inputs to i8 vector of correct length to match PALIGNR or
12279 // PSLLDQ/PSRLDQ.
12280 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12281 Lo = DAG.getBitcast(ByteVT, Lo);
12282 Hi = DAG.getBitcast(ByteVT, Hi);
12283
12284 // SSSE3 targets can use the palignr instruction.
12285 if (Subtarget.hasSSSE3()) {
12286 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
12287 "512-bit PALIGNR requires BWI instructions");
12288 return DAG.getBitcast(
12289 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12290 DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12291 }
12292
12293 assert(VT.is128BitVector() &&
12294 "Rotate-based lowering only supports 128-bit lowering!");
12295 assert(Mask.size() <= 16 &&
12296 "Can shuffle at most 16 bytes in a 128-bit vector!");
12297 assert(ByteVT == MVT::v16i8 &&
12298 "SSE2 rotate lowering only needed for v16i8!");
12299
12300 // Default SSE2 implementation
12301 int LoByteShift = 16 - ByteRotation;
12302 int HiByteShift = ByteRotation;
12303
12304 SDValue LoShift =
12305 DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12306 DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12307 SDValue HiShift =
12308 DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12309 DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12310 return DAG.getBitcast(VT,
12311 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12312}
12313
12314/// Try to lower a vector shuffle as a dword/qword rotation.
12315///
12316/// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12317/// rotation of the concatenation of two vectors; This routine will
12318/// try to generically lower a vector shuffle through such an pattern.
12319///
12320/// Essentially it concatenates V1 and V2, shifts right by some number of
12321/// elements, and takes the low elements as the result. Note that while this is
12322/// specified as a *right shift* because x86 is little-endian, it is a *left
12323/// rotate* of the vector lanes.
12325 SDValue V2, ArrayRef<int> Mask,
12326 const APInt &Zeroable,
12327 const X86Subtarget &Subtarget,
12328 SelectionDAG &DAG) {
12329 unsigned EltBits = VT.getScalarSizeInBits();
12330 if (EltBits != 32 && EltBits != 64)
12331 return SDValue();
12332
12334
12335 // 128/256-bit vectors are only supported with VLX.
12336 assert((Subtarget.hasVLX() ||
12337 (!AlignVT.is128BitVector() && !AlignVT.is256BitVector())) &&
12338 "VLX required for 128/256-bit vectors");
12339
12340 auto emitVALIGN = [&](SDValue Lo, SDValue Hi, unsigned Imm) -> SDValue {
12341 SDValue AlignLo = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Lo) : Lo;
12342 SDValue AlignHi = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Hi) : Hi;
12343 SDValue Res = DAG.getNode(X86ISD::VALIGN, DL, AlignVT, AlignLo, AlignHi,
12344 DAG.getTargetConstant(Imm, DL, MVT::i8));
12345 return VT.isFloatingPoint() ? DAG.getBitcast(VT, Res) : Res;
12346 };
12347
12348 SDValue Lo = V1, Hi = V2;
12349 int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12350 if (0 < Rotation)
12351 return emitVALIGN(Lo, Hi, Rotation);
12352
12353 // See if we can use VALIGN as a cross-lane version of VSHLDQ/VSRLDQ.
12354 // TODO: Pull this out as a matchShuffleAsElementShift helper?
12355 // TODO: We can probably make this more aggressive and use shift-pairs like
12356 // lowerShuffleAsByteShiftMask.
12357 unsigned NumElts = Mask.size();
12358 unsigned ZeroLo = Zeroable.countr_one();
12359 unsigned ZeroHi = Zeroable.countl_one();
12360 assert((ZeroLo + ZeroHi) < NumElts && "Zeroable shuffle detected");
12361 if (!ZeroLo && !ZeroHi)
12362 return SDValue();
12363
12364 if (ZeroLo) {
12365 SDValue Src = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12366 int Low = Mask[ZeroLo] < (int)NumElts ? 0 : NumElts;
12367 if (isSequentialOrUndefInRange(Mask, ZeroLo, NumElts - ZeroLo, Low))
12368 return emitVALIGN(Src, getZeroVector(AlignVT, Subtarget, DAG, DL),
12369 NumElts - ZeroLo);
12370 }
12371
12372 if (ZeroHi) {
12373 SDValue Src = Mask[0] < (int)NumElts ? V1 : V2;
12374 int Low = Mask[0] < (int)NumElts ? 0 : NumElts;
12375 if (isSequentialOrUndefInRange(Mask, 0, NumElts - ZeroHi, Low + ZeroHi))
12376 return emitVALIGN(getZeroVector(AlignVT, Subtarget, DAG, DL), Src,
12377 ZeroHi);
12378 }
12379
12380 return SDValue();
12381}
12382
12383/// Try to lower a vector shuffle as a byte shift sequence.
12385 SDValue V2, ArrayRef<int> Mask,
12386 const APInt &Zeroable,
12387 const X86Subtarget &Subtarget,
12388 SelectionDAG &DAG) {
12389 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12390 assert(VT.is128BitVector() && "Only 128-bit vectors supported");
12391
12392 // We need a shuffle that has zeros at one/both ends and a sequential
12393 // shuffle from one source within.
12394 unsigned ZeroLo = Zeroable.countr_one();
12395 unsigned ZeroHi = Zeroable.countl_one();
12396 if (!ZeroLo && !ZeroHi)
12397 return SDValue();
12398
12399 unsigned NumElts = Mask.size();
12400 unsigned Len = NumElts - (ZeroLo + ZeroHi);
12401 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12402 return SDValue();
12403
12404 unsigned Scale = VT.getScalarSizeInBits() / 8;
12405 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12406 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12407 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12408 return SDValue();
12409
12410 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12411 Res = DAG.getBitcast(MVT::v16i8, Res);
12412
12413 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12414 // inner sequential set of elements, possibly offset:
12415 // 01234567 --> zzzzzz01 --> 1zzzzzzz
12416 // 01234567 --> 4567zzzz --> zzzzz456
12417 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12418 if (ZeroLo == 0) {
12419 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12420 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12421 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12422 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12423 DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12424 } else if (ZeroHi == 0) {
12425 unsigned Shift = Mask[ZeroLo] % NumElts;
12426 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12427 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12428 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12429 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12430 } else if (!Subtarget.hasSSSE3()) {
12431 // If we don't have PSHUFB then its worth avoiding an AND constant mask
12432 // by performing 3 byte shifts. Shuffle combining can kick in above that.
12433 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12434 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12435 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12436 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12437 Shift += Mask[ZeroLo] % NumElts;
12438 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12439 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12440 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12441 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12442 } else
12443 return SDValue();
12444
12445 return DAG.getBitcast(VT, Res);
12446}
12447
12448/// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12449///
12450/// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12451/// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12452/// matches elements from one of the input vectors shuffled to the left or
12453/// right with zeroable elements 'shifted in'. It handles both the strictly
12454/// bit-wise element shifts and the byte shift across an entire 128-bit double
12455/// quad word lane.
12456///
12457/// PSHL : (little-endian) left bit shift.
12458/// [ zz, 0, zz, 2 ]
12459/// [ -1, 4, zz, -1 ]
12460/// PSRL : (little-endian) right bit shift.
12461/// [ 1, zz, 3, zz]
12462/// [ -1, -1, 7, zz]
12463/// PSLLDQ : (little-endian) left byte shift
12464/// [ zz, 0, 1, 2, 3, 4, 5, 6]
12465/// [ zz, zz, -1, -1, 2, 3, 4, -1]
12466/// [ zz, zz, zz, zz, zz, zz, -1, 1]
12467/// PSRLDQ : (little-endian) right byte shift
12468/// [ 5, 6, 7, zz, zz, zz, zz, zz]
12469/// [ -1, 5, 6, 7, zz, zz, zz, zz]
12470/// [ 1, 2, -1, -1, -1, -1, zz, zz]
12471static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12472 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12473 int MaskOffset, const APInt &Zeroable,
12474 const X86Subtarget &Subtarget) {
12475 int Size = Mask.size();
12476 unsigned SizeInBits = Size * ScalarSizeInBits;
12477
12478 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12479 for (int i = 0; i < Size; i += Scale)
12480 for (int j = 0; j < Shift; ++j)
12481 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12482 return false;
12483
12484 return true;
12485 };
12486
12487 auto MatchShift = [&](int Shift, int Scale, bool Left) {
12488 for (int i = 0; i != Size; i += Scale) {
12489 unsigned Pos = Left ? i + Shift : i;
12490 unsigned Low = Left ? i : i + Shift;
12491 unsigned Len = Scale - Shift;
12492 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12493 return -1;
12494 }
12495
12496 int ShiftEltBits = ScalarSizeInBits * Scale;
12497 bool ByteShift = ShiftEltBits > 64;
12498 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12499 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12500 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12501
12502 // Normalize the scale for byte shifts to still produce an i64 element
12503 // type.
12504 Scale = ByteShift ? Scale / 2 : Scale;
12505
12506 // We need to round trip through the appropriate type for the shift.
12507 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12508 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12509 : MVT::getVectorVT(ShiftSVT, Size / Scale);
12510 return ShiftAmt;
12511 };
12512
12513 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12514 // keep doubling the size of the integer elements up to that. We can
12515 // then shift the elements of the integer vector by whole multiples of
12516 // their width within the elements of the larger integer vector. Test each
12517 // multiple to see if we can find a match with the moved element indices
12518 // and that the shifted in elements are all zeroable.
12519 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12520 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12521 for (int Shift = 1; Shift != Scale; ++Shift)
12522 for (bool Left : {true, false})
12523 if (CheckZeros(Shift, Scale, Left)) {
12524 int ShiftAmt = MatchShift(Shift, Scale, Left);
12525 if (0 < ShiftAmt)
12526 return ShiftAmt;
12527 }
12528
12529 // no match
12530 return -1;
12531}
12532
12534 SDValue V2, ArrayRef<int> Mask,
12535 const APInt &Zeroable,
12536 const X86Subtarget &Subtarget,
12537 SelectionDAG &DAG, bool BitwiseOnly) {
12538 int Size = Mask.size();
12539 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12540
12541 MVT ShiftVT;
12542 SDValue V = V1;
12543 unsigned Opcode;
12544
12545 // Try to match shuffle against V1 shift.
12546 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12547 Mask, 0, Zeroable, Subtarget);
12548
12549 // If V1 failed, try to match shuffle against V2 shift.
12550 if (ShiftAmt < 0) {
12551 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12552 Mask, Size, Zeroable, Subtarget);
12553 V = V2;
12554 }
12555
12556 if (ShiftAmt < 0)
12557 return SDValue();
12558
12559 if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
12560 return SDValue();
12561
12562 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
12563 "Illegal integer vector type");
12564 V = DAG.getBitcast(ShiftVT, V);
12565 V = DAG.getNode(Opcode, DL, ShiftVT, V,
12566 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12567 return DAG.getBitcast(VT, V);
12568}
12569
12570/// Try to match a vector shuffle as a X86ISD::VSHLD funnel shift.
12571static int matchShuffleAsVSHLD(MVT &ShiftVT, SDValue &V1, SDValue &V2,
12572 unsigned ScalarSizeInBits, ArrayRef<int> Mask) {
12573 assert(isPowerOf2_32(ScalarSizeInBits) && ScalarSizeInBits >= 8 &&
12574 "Unexpected element size");
12575 int Size = Mask.size();
12577 return -1;
12578
12579 SmallVector<int, 32> FunnelMask(Size);
12580 for (int Scale = 2; (Scale * ScalarSizeInBits) <= 64; Scale *= 2) {
12581 for (int Shift = 1; Shift != Scale; ++Shift) {
12582 for (int Elt = 0; Elt != Size; Elt += Scale) {
12583 std::iota(FunnelMask.begin() + Elt, FunnelMask.begin() + Elt + Shift,
12584 Elt + Size + (Scale - Shift));
12585 std::iota(FunnelMask.begin() + Elt + Shift,
12586 FunnelMask.begin() + Elt + Scale, Elt);
12587 }
12588 if (isShuffleEquivalent(Mask, FunnelMask)) {
12589 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12590 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12591 return Shift * ScalarSizeInBits;
12592 }
12594 if (isShuffleEquivalent(Mask, FunnelMask)) {
12595 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12596 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12597 std::swap(V1, V2);
12598 return Shift * ScalarSizeInBits;
12599 }
12600 }
12601 }
12602
12603 return -1;
12604}
12605
12606// EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12607// Remainder of lower half result is zero and upper half is all undef.
12609 ArrayRef<int> Mask, uint64_t &BitLen,
12610 uint64_t &BitIdx, const APInt &Zeroable) {
12611 int Size = Mask.size();
12612 int HalfSize = Size / 2;
12613 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12614 assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
12615
12616 // Upper half must be undefined.
12617 if (!isUndefUpperHalf(Mask))
12618 return false;
12619
12620 // Determine the extraction length from the part of the
12621 // lower half that isn't zeroable.
12622 int Len = HalfSize;
12623 for (; Len > 0; --Len)
12624 if (!Zeroable[Len - 1])
12625 break;
12626 assert(Len > 0 && "Zeroable shuffle mask");
12627
12628 // Attempt to match first Len sequential elements from the lower half.
12629 SDValue Src;
12630 int Idx = -1;
12631 for (int i = 0; i != Len; ++i) {
12632 int M = Mask[i];
12633 if (M == SM_SentinelUndef)
12634 continue;
12635 SDValue &V = (M < Size ? V1 : V2);
12636 M = M % Size;
12637
12638 // The extracted elements must start at a valid index and all mask
12639 // elements must be in the lower half.
12640 if (i > M || M >= HalfSize)
12641 return false;
12642
12643 if (Idx < 0 || (Src == V && Idx == (M - i))) {
12644 Src = V;
12645 Idx = M - i;
12646 continue;
12647 }
12648 return false;
12649 }
12650
12651 if (!Src || Idx < 0)
12652 return false;
12653
12654 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12655 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12656 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12657 V1 = Src;
12658 return true;
12659}
12660
12661// INSERTQ: Extract lowest Len elements from lower half of second source and
12662// insert over first source, starting at Idx.
12663// { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
12665 ArrayRef<int> Mask, uint64_t &BitLen,
12666 uint64_t &BitIdx) {
12667 int Size = Mask.size();
12668 int HalfSize = Size / 2;
12669 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12670
12671 // Upper half must be undefined.
12672 if (!isUndefUpperHalf(Mask))
12673 return false;
12674
12675 for (int Idx = 0; Idx != HalfSize; ++Idx) {
12676 SDValue Base;
12677
12678 // Attempt to match first source from mask before insertion point.
12679 if (isUndefInRange(Mask, 0, Idx)) {
12680 /* EMPTY */
12681 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12682 Base = V1;
12683 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12684 Base = V2;
12685 } else {
12686 continue;
12687 }
12688
12689 // Extend the extraction length looking to match both the insertion of
12690 // the second source and the remaining elements of the first.
12691 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12692 SDValue Insert;
12693 int Len = Hi - Idx;
12694
12695 // Match insertion.
12696 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12697 Insert = V1;
12698 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12699 Insert = V2;
12700 } else {
12701 continue;
12702 }
12703
12704 // Match the remaining elements of the lower half.
12705 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12706 /* EMPTY */
12707 } else if ((!Base || (Base == V1)) &&
12708 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12709 Base = V1;
12710 } else if ((!Base || (Base == V2)) &&
12711 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12712 Size + Hi)) {
12713 Base = V2;
12714 } else {
12715 continue;
12716 }
12717
12718 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12719 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12720 V1 = Base;
12721 V2 = Insert;
12722 return true;
12723 }
12724 }
12725
12726 return false;
12727}
12728
12729/// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
12731 SDValue V2, ArrayRef<int> Mask,
12732 const APInt &Zeroable, SelectionDAG &DAG) {
12733 uint64_t BitLen, BitIdx;
12734 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12735 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12736 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12737 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12738
12739 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12740 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12741 V2 ? V2 : DAG.getUNDEF(VT),
12742 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12743 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12744
12745 return SDValue();
12746}
12747
12748/// Lower a vector shuffle as an any/signed/zero extension.
12749///
12750/// Given a specific number of elements, element bit width, and extension
12751/// stride, produce either an extension based on the available
12752/// features of the subtarget. The extended elements are consecutive and
12753/// begin and can start from an offsetted element index in the input; to
12754/// avoid excess shuffling the offset must either being in the bottom lane
12755/// or at the start of a higher lane. All extended elements must be from
12756/// the same lane.
12758 int Scale, int Offset,
12759 unsigned ExtOpc, SDValue InputV,
12760 ArrayRef<int> Mask,
12761 const X86Subtarget &Subtarget,
12762 SelectionDAG &DAG) {
12763 assert(Scale > 1 && "Need a scale to extend.");
12764 assert(ISD::isExtOpcode(ExtOpc) && "Unsupported extension");
12765 int EltBits = VT.getScalarSizeInBits();
12766 int NumElements = VT.getVectorNumElements();
12767 int NumEltsPerLane = 128 / EltBits;
12768 int OffsetLane = Offset / NumEltsPerLane;
12769 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12770 "Only 8, 16, and 32 bit elements can be extended.");
12771 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12772 assert(0 <= Offset && "Extension offset must be positive.");
12773 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12774 "Extension offset must be in the first lane or start an upper lane.");
12775
12776 // Check that an index is in same lane as the base offset.
12777 auto SafeOffset = [&](int Idx) {
12778 return OffsetLane == (Idx / NumEltsPerLane);
12779 };
12780
12781 // Shift along an input so that the offset base moves to the first element.
12782 auto ShuffleOffset = [&](SDValue V) {
12783 if (!Offset)
12784 return V;
12785
12786 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12787 for (int i = 0; i * Scale < NumElements; ++i) {
12788 int SrcIdx = i + Offset;
12789 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12790 }
12791 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12792 };
12793
12794 // Found a valid a/zext mask! Try various lowering strategies based on the
12795 // input type and available ISA extensions.
12796 if (Subtarget.hasSSE41()) {
12797 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12798 // PUNPCK will catch this in a later shuffle match.
12799 if (Offset && Scale == 2 && VT.is128BitVector())
12800 return SDValue();
12801 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12802 NumElements / Scale);
12803 InputV = DAG.getBitcast(VT, InputV);
12804 InputV = ShuffleOffset(InputV);
12805 InputV = getEXTEND_VECTOR_INREG(ExtOpc, DL, ExtVT, InputV, DAG);
12806 return DAG.getBitcast(VT, InputV);
12807 }
12808
12809 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12810 InputV = DAG.getBitcast(VT, InputV);
12811 bool AnyExt = ExtOpc == ISD::ANY_EXTEND;
12812
12813 // TODO: Add pre-SSE41 SIGN_EXTEND_VECTOR_INREG handling.
12814 if (ExtOpc == ISD::SIGN_EXTEND)
12815 return SDValue();
12816
12817 // For any extends we can cheat for larger element sizes and use shuffle
12818 // instructions that can fold with a load and/or copy.
12819 if (AnyExt && EltBits == 32) {
12820 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12821 -1};
12822 return DAG.getBitcast(
12823 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12824 DAG.getBitcast(MVT::v4i32, InputV),
12825 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12826 }
12827 if (AnyExt && EltBits == 16 && Scale > 2) {
12828 int PSHUFDMask[4] = {Offset / 2, -1,
12829 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12830 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12831 DAG.getBitcast(MVT::v4i32, InputV),
12832 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12833 int PSHUFWMask[4] = {1, -1, -1, -1};
12834 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12835 return DAG.getBitcast(
12836 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12837 DAG.getBitcast(MVT::v8i16, InputV),
12838 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12839 }
12840
12841 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12842 // to 64-bits.
12843 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12844 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12845 assert(VT.is128BitVector() && "Unexpected vector width!");
12846
12847 int LoIdx = Offset * EltBits;
12848 SDValue Lo = DAG.getBitcast(
12849 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12850 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12851 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12852
12853 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12854 return DAG.getBitcast(VT, Lo);
12855
12856 int HiIdx = (Offset + 1) * EltBits;
12857 SDValue Hi = DAG.getBitcast(
12858 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12859 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12860 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12861 return DAG.getBitcast(VT,
12862 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12863 }
12864
12865 // If this would require more than 2 unpack instructions to expand, use
12866 // pshufb when available. We can only use more than 2 unpack instructions
12867 // when zero extending i8 elements which also makes it easier to use pshufb.
12868 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12869 assert(NumElements == 16 && "Unexpected byte vector width!");
12870 SDValue PSHUFBMask[16];
12871 for (int i = 0; i < 16; ++i) {
12872 int Idx = Offset + (i / Scale);
12873 if ((i % Scale == 0 && SafeOffset(Idx))) {
12874 PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12875 continue;
12876 }
12877 PSHUFBMask[i] =
12878 AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12879 }
12880 InputV = DAG.getBitcast(MVT::v16i8, InputV);
12881 return DAG.getBitcast(
12882 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12883 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12884 }
12885
12886 // If we are extending from an offset, ensure we start on a boundary that
12887 // we can unpack from.
12888 int AlignToUnpack = Offset % (NumElements / Scale);
12889 if (AlignToUnpack) {
12890 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12891 for (int i = AlignToUnpack; i < NumElements; ++i)
12892 ShMask[i - AlignToUnpack] = i;
12893 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12894 Offset -= AlignToUnpack;
12895 }
12896
12897 // Otherwise emit a sequence of unpacks.
12898 do {
12899 unsigned UnpackLoHi = X86ISD::UNPCKL;
12900 if (Offset >= (NumElements / 2)) {
12901 UnpackLoHi = X86ISD::UNPCKH;
12902 Offset -= (NumElements / 2);
12903 }
12904
12905 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12906 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12907 : getZeroVector(InputVT, Subtarget, DAG, DL);
12908 InputV = DAG.getBitcast(InputVT, InputV);
12909 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12910 Scale /= 2;
12911 EltBits *= 2;
12912 NumElements /= 2;
12913 } while (Scale > 1);
12914 return DAG.getBitcast(VT, InputV);
12915}
12916
12917/// Try to lower a vector shuffle as a zero extension on any microarch.
12918///
12919/// This routine will try to do everything in its power to cleverly lower
12920/// a shuffle which happens to match the pattern of a zero extend. It doesn't
12921/// check for the profitability of this lowering, it tries to aggressively
12922/// match this pattern. It will use all of the micro-architectural details it
12923/// can to emit an efficient lowering. It handles both blends with all-zero
12924/// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12925/// masking out later).
12926///
12927/// The reason we have dedicated lowering for zext-style shuffles is that they
12928/// are both incredibly common and often quite performance sensitive.
12930 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12931 const APInt &Zeroable, const X86Subtarget &Subtarget,
12932 SelectionDAG &DAG) {
12933 int Bits = VT.getSizeInBits();
12934 int NumLanes = Bits / 128;
12935 int NumElements = VT.getVectorNumElements();
12936 int NumEltsPerLane = NumElements / NumLanes;
12937 assert(VT.getScalarSizeInBits() <= 32 &&
12938 "Exceeds 32-bit integer zero extension limit");
12939 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12940
12941 // Define a helper function to check a particular ext-scale and lower to it if
12942 // valid.
12943 auto Lower = [&](int Scale) -> SDValue {
12944 SDValue InputV;
12945 bool AnyExt = true;
12946 int Offset = 0;
12947 int Matches = 0;
12948 for (int i = 0; i < NumElements; ++i) {
12949 int M = Mask[i];
12950 if (M < 0)
12951 continue; // Valid anywhere but doesn't tell us anything.
12952 if (i % Scale != 0) {
12953 // Each of the extended elements need to be zeroable.
12954 if (!Zeroable[i])
12955 return SDValue();
12956
12957 // We no longer are in the anyext case.
12958 AnyExt = false;
12959 continue;
12960 }
12961
12962 // Each of the base elements needs to be consecutive indices into the
12963 // same input vector.
12964 SDValue V = M < NumElements ? V1 : V2;
12965 M = M % NumElements;
12966 if (!InputV) {
12967 InputV = V;
12968 Offset = M - (i / Scale);
12969 } else if (InputV != V)
12970 return SDValue(); // Flip-flopping inputs.
12971
12972 // Offset must start in the lowest 128-bit lane or at the start of an
12973 // upper lane.
12974 // FIXME: Is it ever worth allowing a negative base offset?
12975 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12976 (Offset % NumEltsPerLane) == 0))
12977 return SDValue();
12978
12979 // If we are offsetting, all referenced entries must come from the same
12980 // lane.
12981 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12982 return SDValue();
12983
12984 if ((M % NumElements) != (Offset + (i / Scale)))
12985 return SDValue(); // Non-consecutive strided elements.
12986 Matches++;
12987 }
12988
12989 // If we fail to find an input, we have a zero-shuffle which should always
12990 // have already been handled.
12991 // FIXME: Maybe handle this here in case during blending we end up with one?
12992 if (!InputV)
12993 return SDValue();
12994
12995 // If we are offsetting, don't extend if we only match a single input, we
12996 // can always do better by using a basic PSHUF or PUNPCK.
12997 if (Offset != 0 && Matches < 2)
12998 return SDValue();
12999
13000 unsigned ExtOpc = AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND;
13001 return lowerShuffleAsSpecificExtension(DL, VT, Scale, Offset, ExtOpc,
13002 InputV, Mask, Subtarget, DAG);
13003 };
13004
13005 // Match against a foldable v4i32 VZEXT_MOVL zero-extending instruction.
13006 // TODO: Add v8i16 (with FP16) support when we have test coverage.
13007 if (VT == MVT::v4i32 &&
13008 (V1.getOpcode() == ISD::SCALAR_TO_VECTOR || isa<MemSDNode>(V1)) &&
13009 Mask[0] == 0 && (NumElements - 1) == (int)Zeroable.countLeadingOnes())
13010 return DAG.getNode(X86ISD::VZEXT_MOVL, DL, VT, V1);
13011
13012 // The widest scale possible for extending is to a 64-bit integer.
13013 assert(Bits % 64 == 0 &&
13014 "The number of bits in a vector must be divisible by 64 on x86!");
13015 int NumExtElements = Bits / 64;
13016
13017 // Each iteration, try extending the elements half as much, but into twice as
13018 // many elements.
13019 for (; NumExtElements < NumElements; NumExtElements *= 2) {
13020 assert(NumElements % NumExtElements == 0 &&
13021 "The input vector size must be divisible by the extended size.");
13022 if (SDValue V = Lower(NumElements / NumExtElements))
13023 return V;
13024 }
13025
13026 // General extends failed, but 128-bit vectors may be able to use MOVQ.
13027 if (Bits != 128)
13028 return SDValue();
13029
13030 // Returns one of the source operands if the shuffle can be reduced to a
13031 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13032 auto CanZExtLowHalf = [&]() {
13033 for (int i = NumElements / 2; i != NumElements; ++i)
13034 if (!Zeroable[i])
13035 return SDValue();
13036 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13037 return V1;
13038 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13039 return V2;
13040 return SDValue();
13041 };
13042
13043 if (SDValue V = CanZExtLowHalf()) {
13044 V = DAG.getBitcast(MVT::v2i64, V);
13045 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13046 return DAG.getBitcast(VT, V);
13047 }
13048
13049 // No viable ext lowering found.
13050 return SDValue();
13051}
13052
13053/// Try to get a scalar value for a specific element of a vector.
13054///
13055/// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13057 SelectionDAG &DAG) {
13058 MVT VT = V.getSimpleValueType();
13059 MVT EltVT = VT.getVectorElementType();
13061
13062 // If the bitcasts shift the element size, we can't extract an equivalent
13063 // element from it.
13064 MVT NewVT = V.getSimpleValueType();
13065 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13066 return SDValue();
13067
13068 if (V.getOpcode() == ISD::BUILD_VECTOR ||
13069 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13070 // Ensure the scalar operand is the same size as the destination.
13071 // FIXME: Add support for scalar truncation where possible.
13072 SDValue S = V.getOperand(Idx);
13073 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13074 return DAG.getBitcast(EltVT, S);
13075 }
13076
13077 return SDValue();
13078}
13079
13080/// Helper to test for a load that can be folded with x86 shuffles.
13081///
13082/// This is particularly important because the set of instructions varies
13083/// significantly based on whether the operand is a load or not.
13085 return V.hasOneUse() &&
13087}
13088
13089template<typename T>
13090static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
13091 T EltVT = VT.getScalarType();
13092 return (EltVT == MVT::bf16 && !Subtarget.hasAVX10_2()) ||
13093 (EltVT == MVT::f16 && !Subtarget.hasFP16());
13094}
13095
13096template<typename T>
13097static bool isBF16orSoftF16(T VT, const X86Subtarget &Subtarget) {
13098 T EltVT = VT.getScalarType();
13099 return EltVT == MVT::bf16 || (EltVT == MVT::f16 && !Subtarget.hasFP16());
13100}
13101
13102/// Try to lower insertion of a single element into a zero vector.
13103///
13104/// This is a common pattern that we have especially efficient patterns to lower
13105/// across all subtarget feature sets.
13107 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13108 const APInt &Zeroable, const X86Subtarget &Subtarget,
13109 SelectionDAG &DAG) {
13110 MVT ExtVT = VT;
13111 MVT EltVT = VT.getVectorElementType();
13112 unsigned NumElts = VT.getVectorNumElements();
13113 unsigned EltBits = VT.getScalarSizeInBits();
13114
13115 if (isSoftF16(EltVT, Subtarget))
13116 return SDValue();
13117
13118 int V2Index =
13119 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13120 Mask.begin();
13121 bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
13122 bool IsV1Zeroable = true;
13123 for (int i = 0, Size = Mask.size(); i < Size; ++i)
13124 if (i != V2Index && !Zeroable[i]) {
13125 IsV1Zeroable = false;
13126 break;
13127 }
13128
13129 // Bail if a non-zero V1 isn't used in place.
13130 if (!IsV1Zeroable) {
13131 SmallVector<int, 8> V1Mask(Mask);
13132 V1Mask[V2Index] = -1;
13133 if (!isNoopShuffleMask(V1Mask))
13134 return SDValue();
13135 }
13136
13137 // Check for a single input from a SCALAR_TO_VECTOR node.
13138 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13139 // all the smarts here sunk into that routine. However, the current
13140 // lowering of BUILD_VECTOR makes that nearly impossible until the old
13141 // vector shuffle lowering is dead.
13142 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13143 DAG);
13144 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13145 // We need to zext the scalar if it is smaller than an i32.
13146 V2S = DAG.getBitcast(EltVT, V2S);
13147 if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
13148 // Using zext to expand a narrow element won't work for non-zero
13149 // insertions. But we can use a masked constant vector if we're
13150 // inserting V2 into the bottom of V1.
13151 if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
13152 return SDValue();
13153
13154 // Zero-extend directly to i32.
13155 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13156 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13157
13158 // If we're inserting into a constant, mask off the inserted index
13159 // and OR with the zero-extended scalar.
13160 if (!IsV1Zeroable) {
13161 SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
13162 Bits[V2Index] = APInt::getZero(EltBits);
13163 SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
13164 V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
13165 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13166 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
13167 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
13168 }
13169 }
13170 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13171 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13172 (EltVT == MVT::i16 && !Subtarget.hasAVX10_2())) {
13173 // Either not inserting from the low element of the input or the input
13174 // element size is too small to use VZEXT_MOVL to clear the high bits.
13175 return SDValue();
13176 }
13177
13178 if (!IsV1Zeroable) {
13179 // If V1 can't be treated as a zero vector we have fewer options to lower
13180 // this. We can't support integer vectors or non-zero targets cheaply.
13181 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13182 if (!VT.isFloatingPoint() || V2Index != 0)
13183 return SDValue();
13184 if (!VT.is128BitVector())
13185 return SDValue();
13186
13187 // Otherwise, use MOVSD, MOVSS or MOVSH.
13188 unsigned MovOpc = 0;
13189 if (EltVT == MVT::f16)
13190 MovOpc = X86ISD::MOVSH;
13191 else if (EltVT == MVT::f32)
13192 MovOpc = X86ISD::MOVSS;
13193 else if (EltVT == MVT::f64)
13194 MovOpc = X86ISD::MOVSD;
13195 else
13196 llvm_unreachable("Unsupported floating point element type to handle!");
13197 return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
13198 }
13199
13200 // This lowering only works for the low element with floating point vectors.
13201 if (VT.isFloatingPoint() && V2Index != 0)
13202 return SDValue();
13203
13204 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13205 if (ExtVT != VT)
13206 V2 = DAG.getBitcast(VT, V2);
13207
13208 if (V2Index != 0) {
13209 // If we have 4 or fewer lanes we can cheaply shuffle the element into
13210 // the desired position. Otherwise it is more efficient to do a vector
13211 // shift left. We know that we can do a vector shift left because all
13212 // the inputs are zero.
13213 if (VT.isFloatingPoint() || NumElts <= 4) {
13214 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13215 V2Shuffle[V2Index] = 0;
13216 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13217 } else {
13218 V2 = DAG.getBitcast(MVT::v16i8, V2);
13219 V2 = DAG.getNode(
13220 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13221 DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
13222 V2 = DAG.getBitcast(VT, V2);
13223 }
13224 }
13225 return V2;
13226}
13227
13228/// Try to lower broadcast of a single - truncated - integer element,
13229/// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13230///
13231/// This assumes we have AVX2.
13233 int BroadcastIdx,
13234 const X86Subtarget &Subtarget,
13235 SelectionDAG &DAG) {
13236 assert(Subtarget.hasAVX2() &&
13237 "We can only lower integer broadcasts with AVX2!");
13238
13239 MVT EltVT = VT.getVectorElementType();
13240 MVT V0VT = V0.getSimpleValueType();
13241
13242 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
13243 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
13244
13245 MVT V0EltVT = V0VT.getVectorElementType();
13246 if (!V0EltVT.isInteger())
13247 return SDValue();
13248
13249 const unsigned EltSize = EltVT.getSizeInBits();
13250 const unsigned V0EltSize = V0EltVT.getSizeInBits();
13251
13252 // This is only a truncation if the original element type is larger.
13253 if (V0EltSize <= EltSize)
13254 return SDValue();
13255
13256 assert(((V0EltSize % EltSize) == 0) &&
13257 "Scalar type sizes must all be powers of 2 on x86!");
13258
13259 const unsigned V0Opc = V0.getOpcode();
13260 const unsigned Scale = V0EltSize / EltSize;
13261 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13262
13263 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13264 V0Opc != ISD::BUILD_VECTOR)
13265 return SDValue();
13266
13267 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13268
13269 // If we're extracting non-least-significant bits, shift so we can truncate.
13270 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13271 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13272 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13273 if (const int OffsetIdx = BroadcastIdx % Scale)
13274 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13275 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13276
13277 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13278 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13279}
13280
13281/// Test whether this can be lowered with a single SHUFPS instruction.
13282///
13283/// This is used to disable more specialized lowerings when the shufps lowering
13284/// will happen to be efficient.
13286 // This routine only handles 128-bit shufps.
13287 assert(Mask.size() == 4 && "Unsupported mask size!");
13288 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
13289 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
13290 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
13291 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
13292
13293 // To lower with a single SHUFPS we need to have the low half and high half
13294 // each requiring a single input.
13295 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13296 return false;
13297 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13298 return false;
13299
13300 return true;
13301}
13302
13303/// Test whether the specified input (0 or 1) is in-place blended by the
13304/// given mask.
13305///
13306/// This returns true if the elements from a particular input are already in the
13307/// slot required by the given mask and require no permutation.
13309 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
13310 int Size = Mask.size();
13311 for (int i = 0; i < Size; ++i)
13312 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
13313 return false;
13314
13315 return true;
13316}
13317
13318/// Test whether the specified input (0 or 1) is a broadcast/splat blended by
13319/// the given mask.
13320///
13322 int BroadcastableElement = 0) {
13323 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
13324 int Size = Mask.size();
13325 for (int i = 0; i < Size; ++i)
13326 if (Mask[i] >= 0 && Mask[i] / Size == Input &&
13327 Mask[i] % Size != BroadcastableElement)
13328 return false;
13329 return true;
13330}
13331
13332/// If we are extracting two 128-bit halves of a vector and shuffling the
13333/// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13334/// multi-shuffle lowering.
13336 SDValue N1, ArrayRef<int> Mask,
13337 SelectionDAG &DAG) {
13338 MVT VT = N0.getSimpleValueType();
13339 assert((VT.is128BitVector() &&
13340 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
13341 "VPERM* family of shuffles requires 32-bit or 64-bit elements");
13342
13343 // Check that both sources are extracts of the same source vector.
13344 if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13346 N0.getOperand(0) != N1.getOperand(0) ||
13347 !N0.hasOneUse() || !N1.hasOneUse())
13348 return SDValue();
13349
13350 SDValue WideVec = N0.getOperand(0);
13351 MVT WideVT = WideVec.getSimpleValueType();
13352 if (!WideVT.is256BitVector())
13353 return SDValue();
13354
13355 // Match extracts of each half of the wide source vector. Commute the shuffle
13356 // if the extract of the low half is N1.
13357 unsigned NumElts = VT.getVectorNumElements();
13358 SmallVector<int, 4> NewMask(Mask);
13359 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13360 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13361 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13363 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13364 return SDValue();
13365
13366 // Final bailout: if the mask is simple, we are better off using an extract
13367 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13368 // because that avoids a constant load from memory.
13369 if (NumElts == 4 &&
13370 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
13371 return SDValue();
13372
13373 // Extend the shuffle mask with undef elements.
13374 NewMask.append(NumElts, -1);
13375
13376 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13377 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13378 NewMask);
13379 // This is free: ymm -> xmm.
13380 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13381 DAG.getVectorIdxConstant(0, DL));
13382}
13383
13384/// Try to lower broadcast of a single element.
13385///
13386/// For convenience, this code also bundles all of the subtarget feature set
13387/// filtering. While a little annoying to re-dispatch on type here, there isn't
13388/// a convenient way to factor it out.
13390 SDValue V2, ArrayRef<int> Mask,
13391 const X86Subtarget &Subtarget,
13392 SelectionDAG &DAG) {
13393 MVT EltVT = VT.getVectorElementType();
13394 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13395 (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
13396 (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
13397 return SDValue();
13398
13399 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13400 // we can only broadcast from a register with AVX2.
13401 unsigned NumEltBits = VT.getScalarSizeInBits();
13402 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13403 ? X86ISD::MOVDDUP
13404 : X86ISD::VBROADCAST;
13405 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13406
13407 // Check that the mask is a broadcast.
13408 int BroadcastIdx = getSplatIndex(Mask);
13409 if (BroadcastIdx < 0) {
13410 // Check for hidden broadcast.
13411 SmallVector<int, 16> BroadcastMask(VT.getVectorNumElements(), 0);
13412 if (!isShuffleEquivalent(Mask, BroadcastMask, V1, V2))
13413 return SDValue();
13414 BroadcastIdx = 0;
13415 }
13416 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
13417 "a sorted mask where the broadcast "
13418 "comes from V1.");
13419 int NumActiveElts = count_if(Mask, [](int M) { return M >= 0; });
13420
13421 // Go up the chain of (vector) values to find a scalar load that we can
13422 // combine with the broadcast.
13423 // TODO: Combine this logic with findEltLoadSrc() used by
13424 // EltsFromConsecutiveLoads().
13425 int BitOffset = BroadcastIdx * NumEltBits;
13426 SDValue V = V1;
13427 for (;;) {
13428 switch (V.getOpcode()) {
13429 case ISD::BITCAST: {
13430 V = V.getOperand(0);
13431 continue;
13432 }
13433 case ISD::CONCAT_VECTORS: {
13434 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13435 int OpIdx = BitOffset / OpBitWidth;
13436 V = V.getOperand(OpIdx);
13437 BitOffset %= OpBitWidth;
13438 continue;
13439 }
13441 // The extraction index adds to the existing offset.
13442 unsigned EltBitWidth = V.getScalarValueSizeInBits();
13443 unsigned Idx = V.getConstantOperandVal(1);
13444 unsigned BeginOffset = Idx * EltBitWidth;
13445 BitOffset += BeginOffset;
13446 V = V.getOperand(0);
13447 continue;
13448 }
13449 case ISD::INSERT_SUBVECTOR: {
13450 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13451 int EltBitWidth = VOuter.getScalarValueSizeInBits();
13452 int Idx = (int)V.getConstantOperandVal(2);
13453 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13454 int BeginOffset = Idx * EltBitWidth;
13455 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13456 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13457 BitOffset -= BeginOffset;
13458 V = VInner;
13459 } else {
13460 V = VOuter;
13461 }
13462 continue;
13463 }
13464 }
13465 break;
13466 }
13467 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
13468 BroadcastIdx = BitOffset / NumEltBits;
13469
13470 // Do we need to bitcast the source to retrieve the original broadcast index?
13471 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13472
13473 // Check if this is a broadcast of a scalar. We special case lowering
13474 // for scalars so that we can more effectively fold with loads.
13475 // If the original value has a larger element type than the shuffle, the
13476 // broadcast element is in essence truncated. Make that explicit to ease
13477 // folding.
13478 if (BitCastSrc && VT.isInteger())
13479 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13480 DL, VT, V, BroadcastIdx, Subtarget, DAG))
13481 return TruncBroadcast;
13482
13483 // Also check the simpler case, where we can directly reuse the scalar.
13484 if (!BitCastSrc &&
13485 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13486 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13487 V = V.getOperand(BroadcastIdx);
13488
13489 // If we can't broadcast from a register, check that the input is a load.
13490 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13491 return SDValue();
13492 } else if (ISD::isNormalLoad(V.getNode()) &&
13493 cast<LoadSDNode>(V)->isSimple()) {
13494 // We do not check for one-use of the vector load because a broadcast load
13495 // is expected to be a win for code size, register pressure, and possibly
13496 // uops even if the original vector load is not eliminated.
13497
13498 // Reduce the vector load and shuffle to a broadcasted scalar load.
13499 auto *Ld = cast<LoadSDNode>(V);
13500 SDValue BaseAddr = Ld->getBasePtr();
13501 MVT SVT = VT.getScalarType();
13502 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13503 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
13504 SDValue NewAddr =
13506
13507 // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13508 // than MOVDDUP.
13509 // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13510 if (Opcode == X86ISD::VBROADCAST) {
13511 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13512 SDValue Ops[] = {Ld->getChain(), NewAddr};
13513 V = DAG.getMemIntrinsicNode(
13514 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13516 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13518 return DAG.getBitcast(VT, V);
13519 }
13520 assert(SVT == MVT::f64 && "Unexpected VT!");
13521 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13523 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13525 } else if (!BroadcastFromReg) {
13526 // We can't broadcast from a vector register.
13527 return SDValue();
13528 } else if (BitOffset != 0) {
13529 // We can only broadcast from the zero-element of a vector register,
13530 // but it can be advantageous to broadcast from the zero-element of a
13531 // subvector.
13532 if (!VT.is256BitVector() && !VT.is512BitVector())
13533 return SDValue();
13534
13535 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13536 if (VT == MVT::v4f64 || VT == MVT::v4i64)
13537 return SDValue();
13538
13539 // If we are broadcasting an element from the lowest 128-bit subvector, try
13540 // to move the element in position.
13541 if (BitOffset < 128 && NumActiveElts > 1 &&
13542 V.getScalarValueSizeInBits() == NumEltBits) {
13543 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13544 "Unexpected bit-offset");
13545 SmallVector<int, 16> ExtractMask(128 / NumEltBits, SM_SentinelUndef);
13546 ExtractMask[0] = BitOffset / V.getScalarValueSizeInBits();
13547 V = extractSubVector(V, 0, DAG, DL, 128);
13548 V = DAG.getVectorShuffle(V.getValueType(), DL, V, V, ExtractMask);
13549 } else {
13550 // Only broadcast the zero-element of a 128-bit subvector.
13551 if ((BitOffset % 128) != 0)
13552 return SDValue();
13553
13554 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13555 "Unexpected bit-offset");
13556 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
13557 "Unexpected vector size");
13558 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13559 V = extract128BitVector(V, ExtractIdx, DAG, DL);
13560 }
13561 }
13562
13563 // On AVX we can use VBROADCAST directly for scalar sources.
13564 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
13565 V = DAG.getBitcast(MVT::f64, V);
13566 if (Subtarget.hasAVX()) {
13567 V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
13568 return DAG.getBitcast(VT, V);
13569 }
13570 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
13571 }
13572
13573 // If this is a scalar, do the broadcast on this type and bitcast.
13574 if (!V.getValueType().isVector()) {
13575 assert(V.getScalarValueSizeInBits() == NumEltBits &&
13576 "Unexpected scalar size");
13577 MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13579 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13580 }
13581
13582 // We only support broadcasting from 128-bit vectors to minimize the
13583 // number of patterns we need to deal with in isel. So extract down to
13584 // 128-bits, removing as many bitcasts as possible.
13585 if (V.getValueSizeInBits() > 128)
13587
13588 // Otherwise cast V to a vector with the same element type as VT, but
13589 // possibly narrower than VT. Then perform the broadcast.
13590 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13591 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13592 return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13593}
13594
13595// Check for whether we can use INSERTPS to perform the shuffle. We only use
13596// INSERTPS when the V1 elements are already in the correct locations
13597// because otherwise we can just always use two SHUFPS instructions which
13598// are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13599// perform INSERTPS if a single V1 element is out of place and all V2
13600// elements are zeroable.
13602 unsigned &InsertPSMask,
13603 const APInt &Zeroable,
13604 ArrayRef<int> Mask, SelectionDAG &DAG) {
13605 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
13606 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
13607 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13608
13609 // Attempt to match INSERTPS with one element from VA or VB being
13610 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13611 // are updated.
13612 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13613 ArrayRef<int> CandidateMask) {
13614 unsigned ZMask = 0;
13615 int VADstIndex = -1;
13616 int VBDstIndex = -1;
13617 bool VAUsedInPlace = false;
13618
13619 for (int i = 0; i < 4; ++i) {
13620 // Synthesize a zero mask from the zeroable elements (includes undefs).
13621 if (Zeroable[i]) {
13622 ZMask |= 1 << i;
13623 continue;
13624 }
13625
13626 // Flag if we use any VA inputs in place.
13627 if (i == CandidateMask[i]) {
13628 VAUsedInPlace = true;
13629 continue;
13630 }
13631
13632 // We can only insert a single non-zeroable element.
13633 if (VADstIndex >= 0 || VBDstIndex >= 0)
13634 return false;
13635
13636 if (CandidateMask[i] < 4) {
13637 // VA input out of place for insertion.
13638 VADstIndex = i;
13639 } else {
13640 // VB input for insertion.
13641 VBDstIndex = i;
13642 }
13643 }
13644
13645 // Don't bother if we have no (non-zeroable) element for insertion.
13646 if (VADstIndex < 0 && VBDstIndex < 0)
13647 return false;
13648
13649 // Determine element insertion src/dst indices. The src index is from the
13650 // start of the inserted vector, not the start of the concatenated vector.
13651 unsigned VBSrcIndex = 0;
13652 if (VADstIndex >= 0) {
13653 // If we have a VA input out of place, we use VA as the V2 element
13654 // insertion and don't use the original V2 at all.
13655 VBSrcIndex = CandidateMask[VADstIndex];
13656 VBDstIndex = VADstIndex;
13657 VB = VA;
13658 } else {
13659 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13660 }
13661
13662 // If no V1 inputs are used in place, then the result is created only from
13663 // the zero mask and the V2 insertion - so remove V1 dependency.
13664 if (!VAUsedInPlace)
13665 VA = DAG.getUNDEF(MVT::v4f32);
13666
13667 // Update V1, V2 and InsertPSMask accordingly.
13668 V1 = VA;
13669 V2 = VB;
13670
13671 // Insert the V2 element into the desired position.
13672 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13673 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
13674 return true;
13675 };
13676
13677 if (matchAsInsertPS(V1, V2, Mask))
13678 return true;
13679
13680 // Commute and try again.
13681 SmallVector<int, 4> CommutedMask(Mask);
13683 if (matchAsInsertPS(V2, V1, CommutedMask))
13684 return true;
13685
13686 return false;
13687}
13688
13690 ArrayRef<int> Mask, const APInt &Zeroable,
13691 SelectionDAG &DAG) {
13692 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13693 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13694
13695 // Attempt to match the insertps pattern.
13696 unsigned InsertPSMask = 0;
13697 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13698 return SDValue();
13699
13700 // Insert the V2 element into the desired position.
13701 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13702 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13703}
13704
13705/// Handle lowering of 2-lane 64-bit floating point shuffles.
13706///
13707/// This is the basis function for the 2-lane 64-bit shuffles as we have full
13708/// support for floating point shuffles but not integer shuffles. These
13709/// instructions will incur a domain crossing penalty on some chips though so
13710/// it is better to avoid lowering through this for integer vectors where
13711/// possible.
13713 const APInt &Zeroable, SDValue V1, SDValue V2,
13714 const X86Subtarget &Subtarget,
13715 SelectionDAG &DAG) {
13716 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13717 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13718 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13719
13720 if (V2.isUndef()) {
13721 // Check for being able to broadcast a single element.
13722 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13723 Mask, Subtarget, DAG))
13724 return Broadcast;
13725
13726 // Straight shuffle of a single input vector. Simulate this by using the
13727 // single input as both of the "inputs" to this instruction..
13728 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13729
13730 if (Subtarget.hasAVX()) {
13731 // If we have AVX, we can use VPERMILPS which will allow folding a load
13732 // into the shuffle.
13733 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13734 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13735 }
13736
13737 return DAG.getNode(
13738 X86ISD::SHUFP, DL, MVT::v2f64,
13739 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13740 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13741 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13742 }
13743 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13744 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13745 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13746 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13747
13748 if (Subtarget.hasAVX2())
13749 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13750 return Extract;
13751
13752 // When loading a scalar and then shuffling it into a vector we can often do
13753 // the insertion cheaply.
13755 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13756 return Insertion;
13757 // Try inverting the insertion since for v2 masks it is easy to do and we
13758 // can't reliably sort the mask one way or the other.
13759 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13760 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13762 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13763 return Insertion;
13764
13765 // Try to use one of the special instruction patterns to handle two common
13766 // blend patterns if a zero-blend above didn't work.
13767 if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
13768 isShuffleEquivalent(Mask, {1, 3}, V1, V2))
13769 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13770 // We can either use a special instruction to load over the low double or
13771 // to move just the low double.
13772 return DAG.getNode(
13773 X86ISD::MOVSD, DL, MVT::v2f64, V2,
13774 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13775
13776 if (Subtarget.hasSSE41())
13777 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13778 Zeroable, Subtarget, DAG))
13779 return Blend;
13780
13781 // Use dedicated unpack instructions for masks that match their pattern.
13782 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, V1, V2, Mask, DAG))
13783 return V;
13784
13785 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13786 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13787 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13788}
13789
13790/// Handle lowering of 2-lane 64-bit integer shuffles.
13791///
13792/// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13793/// the integer unit to minimize domain crossing penalties. However, for blends
13794/// it falls back to the floating point shuffle operation with appropriate bit
13795/// casting.
13797 const APInt &Zeroable, SDValue V1, SDValue V2,
13798 const X86Subtarget &Subtarget,
13799 SelectionDAG &DAG) {
13800 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13801 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13802 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13803
13804 if (V2.isUndef()) {
13805 // Check for being able to broadcast a single element.
13806 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13807 Mask, Subtarget, DAG))
13808 return Broadcast;
13809
13810 // Straight shuffle of a single input vector. For everything from SSE2
13811 // onward this has a single fast instruction with no scary immediates.
13812 // We have to map the mask as it is actually a v4i32 shuffle instruction.
13813 V1 = DAG.getBitcast(MVT::v4i32, V1);
13814 int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
13815 Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
13816 Mask[1] < 0 ? -1 : (Mask[1] * 2),
13817 Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
13818 return DAG.getBitcast(
13819 MVT::v2i64,
13820 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13821 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13822 }
13823 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13824 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13825 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13826 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13827
13828 if (Subtarget.hasAVX2())
13829 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13830 return Extract;
13831
13832 // Try to use shift instructions.
13833 if (SDValue Shift =
13834 lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
13835 DAG, /*BitwiseOnly*/ false))
13836 return Shift;
13837
13838 // When loading a scalar and then shuffling it into a vector we can often do
13839 // the insertion cheaply.
13841 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13842 return Insertion;
13843 // Try inverting the insertion since for v2 masks it is easy to do and we
13844 // can't reliably sort the mask one way or the other.
13845 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13847 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13848 return Insertion;
13849
13850 // We have different paths for blend lowering, but they all must use the
13851 // *exact* same predicate.
13852 bool IsBlendSupported = Subtarget.hasSSE41();
13853 if (IsBlendSupported)
13854 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13855 Zeroable, Subtarget, DAG))
13856 return Blend;
13857
13858 // Use dedicated unpack instructions for masks that match their pattern.
13859 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, V1, V2, Mask, DAG))
13860 return V;
13861
13862 // Try to use byte rotation instructions.
13863 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13864 if (Subtarget.hasSSSE3()) {
13865 if (Subtarget.hasVLX())
13866 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
13867 Zeroable, Subtarget, DAG))
13868 return Rotate;
13869
13870 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13871 Subtarget, DAG))
13872 return Rotate;
13873 }
13874
13875 // If we have direct support for blends, we should lower by decomposing into
13876 // a permute. That will be faster than the domain cross.
13877 if (IsBlendSupported)
13878 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
13879 Zeroable, Subtarget, DAG);
13880
13881 // We implement this with SHUFPD which is pretty lame because it will likely
13882 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13883 // However, all the alternatives are still more cycles and newer chips don't
13884 // have this problem. It would be really nice if x86 had better shuffles here.
13885 V1 = DAG.getBitcast(MVT::v2f64, V1);
13886 V2 = DAG.getBitcast(MVT::v2f64, V2);
13887 return DAG.getBitcast(MVT::v2i64,
13888 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13889}
13890
13891/// Lower a vector shuffle using the SHUFPS instruction.
13892///
13893/// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13894/// It makes no assumptions about whether this is the *best* lowering, it simply
13895/// uses it.
13897 ArrayRef<int> Mask, SDValue V1,
13898 SDValue V2, SelectionDAG &DAG) {
13899 SDValue LowV = V1, HighV = V2;
13900 SmallVector<int, 4> NewMask(Mask);
13901 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13902
13903 if (NumV2Elements == 1) {
13904 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13905
13906 // Compute the index adjacent to V2Index and in the same half by toggling
13907 // the low bit.
13908 int V2AdjIndex = V2Index ^ 1;
13909
13910 if (Mask[V2AdjIndex] < 0) {
13911 // Handles all the cases where we have a single V2 element and an undef.
13912 // This will only ever happen in the high lanes because we commute the
13913 // vector otherwise.
13914 if (V2Index < 2)
13915 std::swap(LowV, HighV);
13916 NewMask[V2Index] -= 4;
13917 } else {
13918 // Handle the case where the V2 element ends up adjacent to a V1 element.
13919 // To make this work, blend them together as the first step.
13920 int V1Index = V2AdjIndex;
13921 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13922 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13923 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13924
13925 // Now proceed to reconstruct the final blend as we have the necessary
13926 // high or low half formed.
13927 if (V2Index < 2) {
13928 LowV = V2;
13929 HighV = V1;
13930 } else {
13931 HighV = V2;
13932 }
13933 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13934 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13935 }
13936 } else if (NumV2Elements == 2) {
13937 if (Mask[0] < 4 && Mask[1] < 4) {
13938 // Handle the easy case where we have V1 in the low lanes and V2 in the
13939 // high lanes.
13940 NewMask[2] -= 4;
13941 NewMask[3] -= 4;
13942 } else if (Mask[2] < 4 && Mask[3] < 4) {
13943 // We also handle the reversed case because this utility may get called
13944 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13945 // arrange things in the right direction.
13946 NewMask[0] -= 4;
13947 NewMask[1] -= 4;
13948 HighV = V1;
13949 LowV = V2;
13950 } else {
13951 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13952 // trying to place elements directly, just blend them and set up the final
13953 // shuffle to place them.
13954
13955 // The first two blend mask elements are for V1, the second two are for
13956 // V2.
13957 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13958 Mask[2] < 4 ? Mask[2] : Mask[3],
13959 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13960 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13961 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13962 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13963
13964 // Now we do a normal shuffle of V1 by giving V1 as both operands to
13965 // a blend.
13966 LowV = HighV = V1;
13967 NewMask[0] = Mask[0] < 4 ? 0 : 2;
13968 NewMask[1] = Mask[0] < 4 ? 2 : 0;
13969 NewMask[2] = Mask[2] < 4 ? 1 : 3;
13970 NewMask[3] = Mask[2] < 4 ? 3 : 1;
13971 }
13972 } else if (NumV2Elements == 3) {
13973 // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
13974 // we can get here due to other paths (e.g repeated mask matching) that we
13975 // don't want to do another round of lowerVECTOR_SHUFFLE.
13977 return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
13978 }
13979 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13980 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13981}
13982
13983/// Lower 4-lane 32-bit floating point shuffles.
13984///
13985/// Uses instructions exclusively from the floating point unit to minimize
13986/// domain crossing penalties, as these are sufficient to implement all v4f32
13987/// shuffles.
13989 const APInt &Zeroable, SDValue V1, SDValue V2,
13990 const X86Subtarget &Subtarget,
13991 SelectionDAG &DAG) {
13992 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13993 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13994 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13995
13996 if (Subtarget.hasSSE41())
13997 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13998 Zeroable, Subtarget, DAG))
13999 return Blend;
14000
14001 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14002
14003 if (NumV2Elements == 0) {
14004 // Check for being able to broadcast a single element.
14005 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
14006 Mask, Subtarget, DAG))
14007 return Broadcast;
14008
14009 // Use even/odd duplicate instructions for masks that match their pattern.
14010 if (Subtarget.hasSSE3()) {
14011 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
14012 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
14013 if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
14014 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
14015 }
14016
14017 if (Subtarget.hasAVX()) {
14018 // If we have AVX, we can use VPERMILPS which will allow folding a load
14019 // into the shuffle.
14020 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
14021 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14022 }
14023
14024 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
14025 // in SSE1 because otherwise they are widened to v2f64 and never get here.
14026 if (!Subtarget.hasSSE2()) {
14027 if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14028 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14029 if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14030 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14031 }
14032
14033 // Otherwise, use a straight shuffle of a single input vector. We pass the
14034 // input vector to both operands to simulate this with a SHUFPS.
14035 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14036 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14037 }
14038
14039 if (Subtarget.hasSSE2())
14041 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
14042 ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
14043 return ZExt;
14044 }
14045
14046 if (Subtarget.hasAVX2())
14047 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14048 return Extract;
14049
14050 // There are special ways we can lower some single-element blends. However, we
14051 // have custom ways we can lower more complex single-element blends below that
14052 // we defer to if both this and BLENDPS fail to match, so restrict this to
14053 // when the V2 input is targeting element 0 of the mask -- that is the fast
14054 // case here.
14055 if (NumV2Elements == 1 && Mask[0] >= 4)
14056 if (SDValue V = lowerShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2, Mask,
14057 Zeroable, Subtarget, DAG))
14058 return V;
14059
14060 if (Subtarget.hasSSE41()) {
14061 bool MatchesShufPS = isSingleSHUFPSMask(Mask);
14062
14063 // Use INSERTPS if we can complete the shuffle efficiently.
14064 if (!MatchesShufPS || Zeroable == 0x3 || Zeroable == 0xC)
14065 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14066 return V;
14067
14068 if (!MatchesShufPS)
14069 if (SDValue BlendPerm =
14070 lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1, V2, Mask, DAG))
14071 return BlendPerm;
14072 }
14073
14074 // Use low/high mov instructions. These are only valid in SSE1 because
14075 // otherwise they are widened to v2f64 and never get here.
14076 if (!Subtarget.hasSSE2()) {
14077 if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14078 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14079 if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14080 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14081 }
14082
14083 // Use dedicated unpack instructions for masks that match their pattern.
14084 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, V1, V2, Mask, DAG))
14085 return V;
14086
14087 // Otherwise fall back to a SHUFPS lowering strategy.
14088 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14089}
14090
14091/// Lower 4-lane i32 vector shuffles.
14092///
14093/// We try to handle these with integer-domain shuffles where we can, but for
14094/// blends we use the floating point domain blend instructions.
14096 const APInt &Zeroable, SDValue V1, SDValue V2,
14097 const X86Subtarget &Subtarget,
14098 SelectionDAG &DAG) {
14099 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14100 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14101 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14102
14103 // Whenever we can lower this as a zext, that instruction is strictly faster
14104 // than any alternative. It also allows us to fold memory operands into the
14105 // shuffle in many cases.
14106 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14107 Zeroable, Subtarget, DAG))
14108 return ZExt;
14109
14110 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14111
14112 // Try to use shift instructions if fast.
14113 if (Subtarget.preferLowerShuffleAsShift()) {
14114 if (SDValue Shift =
14115 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
14116 Subtarget, DAG, /*BitwiseOnly*/ true))
14117 return Shift;
14118 if (NumV2Elements == 0)
14119 if (SDValue Rotate =
14120 lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
14121 return Rotate;
14122 }
14123
14124 if (NumV2Elements == 0) {
14125 // Try to use broadcast unless the mask only has one non-undef element.
14126 if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14127 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14128 Mask, Subtarget, DAG))
14129 return Broadcast;
14130 }
14131
14132 // Straight shuffle of a single input vector. For everything from SSE2
14133 // onward this has a single fast instruction with no scary immediates.
14134 // We coerce the shuffle pattern to be compatible with UNPCK instructions
14135 // but we aren't actually going to use the UNPCK instruction because doing
14136 // so prevents folding a load into this instruction or making a copy.
14137 const int UnpackLoMask[] = {0, 0, 1, 1};
14138 const int UnpackHiMask[] = {2, 2, 3, 3};
14139 if (!isSingleElementRepeatedMask(Mask)) {
14140 if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14141 Mask = UnpackLoMask;
14142 else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14143 Mask = UnpackHiMask;
14144 }
14145
14146 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14147 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14148 }
14149
14150 if (Subtarget.hasAVX2())
14151 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14152 return Extract;
14153
14154 // Try to use shift instructions.
14155 if (SDValue Shift =
14156 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
14157 DAG, /*BitwiseOnly*/ false))
14158 return Shift;
14159
14160 // There are special ways we can lower some single-element blends.
14161 if (NumV2Elements == 1)
14163 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14164 return V;
14165
14166 // We have different paths for blend lowering, but they all must use the
14167 // *exact* same predicate.
14168 bool IsBlendSupported = Subtarget.hasSSE41();
14169 if (IsBlendSupported)
14170 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14171 Zeroable, Subtarget, DAG))
14172 return Blend;
14173
14174 if (SDValue Masked =
14175 lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, Zeroable, DAG))
14176 return Masked;
14177
14178 // Use dedicated unpack instructions for masks that match their pattern.
14179 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, V1, V2, Mask, DAG))
14180 return V;
14181
14182 // Try to use byte rotation instructions.
14183 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14184 if (Subtarget.hasSSSE3()) {
14185 if (Subtarget.hasVLX())
14186 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14187 Zeroable, Subtarget, DAG))
14188 return Rotate;
14189
14190 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14191 Subtarget, DAG))
14192 return Rotate;
14193 }
14194
14195 // Assume that a single SHUFPS is faster than an alternative sequence of
14196 // multiple instructions (even if the CPU has a domain penalty).
14197 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14198 if (!isSingleSHUFPSMask(Mask)) {
14199 // If we have direct support for blends, we should lower by decomposing into
14200 // a permute. That will be faster than the domain cross.
14201 if (IsBlendSupported)
14202 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
14203 Zeroable, Subtarget, DAG);
14204
14205 // Try to lower by permuting the inputs into an unpack instruction.
14206 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14207 Mask, Subtarget, DAG))
14208 return Unpack;
14209 }
14210
14211 // We implement this with SHUFPS because it can blend from two vectors.
14212 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14213 // up the inputs, bypassing domain shift penalties that we would incur if we
14214 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14215 // relevant.
14216 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14217 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14218 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14219 return DAG.getBitcast(MVT::v4i32, ShufPS);
14220}
14221
14222/// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14223/// shuffle lowering, and the most complex part.
14224///
14225/// The lowering strategy is to try to form pairs of input lanes which are
14226/// targeted at the same half of the final vector, and then use a dword shuffle
14227/// to place them onto the right half, and finally unpack the paired lanes into
14228/// their final position.
14229///
14230/// The exact breakdown of how to form these dword pairs and align them on the
14231/// correct sides is really tricky. See the comments within the function for
14232/// more of the details.
14233///
14234/// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14235/// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14236/// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14237/// vector, form the analogous 128-bit 8-element Mask.
14239 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14240 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14241 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
14242 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14243
14244 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
14245 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14246 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14247
14248 // Attempt to directly match PSHUFLW or PSHUFHW.
14249 if (isUndefOrInRange(LoMask, 0, 4) &&
14250 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14251 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14252 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14253 }
14254 if (isUndefOrInRange(HiMask, 4, 8) &&
14255 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14256 for (int i = 0; i != 4; ++i)
14257 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14258 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14259 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14260 }
14261
14262 SmallVector<int, 4> LoInputs;
14263 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14264 array_pod_sort(LoInputs.begin(), LoInputs.end());
14265 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
14266 SmallVector<int, 4> HiInputs;
14267 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14268 array_pod_sort(HiInputs.begin(), HiInputs.end());
14269 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
14270 int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14271 int NumHToL = LoInputs.size() - NumLToL;
14272 int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14273 int NumHToH = HiInputs.size() - NumLToH;
14274 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14275 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14276 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14277 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14278
14279 // If we are shuffling values from one half - check how many different DWORD
14280 // pairs we need to create. If only 1 or 2 then we can perform this as a
14281 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14282 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14283 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14284 V = DAG.getNode(ShufWOp, DL, VT, V,
14285 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14286 V = DAG.getBitcast(PSHUFDVT, V);
14287 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14288 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14289 return DAG.getBitcast(VT, V);
14290 };
14291
14292 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14293 int PSHUFDMask[4] = { -1, -1, -1, -1 };
14294 SmallVector<std::pair<int, int>, 4> DWordPairs;
14295 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14296
14297 // Collect the different DWORD pairs.
14298 for (int DWord = 0; DWord != 4; ++DWord) {
14299 int M0 = Mask[2 * DWord + 0];
14300 int M1 = Mask[2 * DWord + 1];
14301 M0 = (M0 >= 0 ? M0 % 4 : M0);
14302 M1 = (M1 >= 0 ? M1 % 4 : M1);
14303 if (M0 < 0 && M1 < 0)
14304 continue;
14305
14306 bool Match = false;
14307 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14308 auto &DWordPair = DWordPairs[j];
14309 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14310 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14311 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14312 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14313 PSHUFDMask[DWord] = DOffset + j;
14314 Match = true;
14315 break;
14316 }
14317 }
14318 if (!Match) {
14319 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14320 DWordPairs.push_back(std::make_pair(M0, M1));
14321 }
14322 }
14323
14324 if (DWordPairs.size() <= 2) {
14325 DWordPairs.resize(2, std::make_pair(-1, -1));
14326 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14327 DWordPairs[1].first, DWordPairs[1].second};
14328 // For splat, ensure we widen the PSHUFDMask to allow vXi64 folds.
14329 if (ShuffleVectorSDNode::isSplatMask(PSHUFDMask) &&
14330 ShuffleVectorSDNode::isSplatMask(PSHUFHalfMask)) {
14331 int SplatIdx = ShuffleVectorSDNode::getSplatMaskIndex(PSHUFHalfMask);
14332 std::fill(PSHUFHalfMask, PSHUFHalfMask + 4, SplatIdx);
14333 PSHUFDMask[0] = PSHUFDMask[2] = DOffset + 0;
14334 PSHUFDMask[1] = PSHUFDMask[3] = DOffset + 1;
14335 }
14336 if ((NumHToL + NumHToH) == 0)
14337 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14338 if ((NumLToL + NumLToH) == 0)
14339 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14340 }
14341 }
14342
14343 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14344 // such inputs we can swap two of the dwords across the half mark and end up
14345 // with <=2 inputs to each half in each half. Once there, we can fall through
14346 // to the generic code below. For example:
14347 //
14348 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14349 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14350 //
14351 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14352 // and an existing 2-into-2 on the other half. In this case we may have to
14353 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14354 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14355 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14356 // because any other situation (including a 3-into-1 or 1-into-3 in the other
14357 // half than the one we target for fixing) will be fixed when we re-enter this
14358 // path. We will also combine away any sequence of PSHUFD instructions that
14359 // result into a single instruction. Here is an example of the tricky case:
14360 //
14361 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14362 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14363 //
14364 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14365 //
14366 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14367 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14368 //
14369 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14370 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14371 //
14372 // The result is fine to be handled by the generic logic.
14373 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14374 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14375 int AOffset, int BOffset) {
14376 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
14377 "Must call this with A having 3 or 1 inputs from the A half.");
14378 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
14379 "Must call this with B having 1 or 3 inputs from the B half.");
14380 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
14381 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
14382
14383 bool ThreeAInputs = AToAInputs.size() == 3;
14384
14385 // Compute the index of dword with only one word among the three inputs in
14386 // a half by taking the sum of the half with three inputs and subtracting
14387 // the sum of the actual three inputs. The difference is the remaining
14388 // slot.
14389 int ADWord = 0, BDWord = 0;
14390 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14391 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14392 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14393 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14394 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14395 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14396 int TripleNonInputIdx =
14397 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14398 TripleDWord = TripleNonInputIdx / 2;
14399
14400 // We use xor with one to compute the adjacent DWord to whichever one the
14401 // OneInput is in.
14402 OneInputDWord = (OneInput / 2) ^ 1;
14403
14404 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14405 // and BToA inputs. If there is also such a problem with the BToB and AToB
14406 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14407 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14408 // is essential that we don't *create* a 3<-1 as then we might oscillate.
14409 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14410 // Compute how many inputs will be flipped by swapping these DWords. We
14411 // need
14412 // to balance this to ensure we don't form a 3-1 shuffle in the other
14413 // half.
14414 int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
14415 llvm::count(AToBInputs, 2 * ADWord + 1);
14416 int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
14417 llvm::count(BToBInputs, 2 * BDWord + 1);
14418 if ((NumFlippedAToBInputs == 1 &&
14419 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14420 (NumFlippedBToBInputs == 1 &&
14421 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14422 // We choose whether to fix the A half or B half based on whether that
14423 // half has zero flipped inputs. At zero, we may not be able to fix it
14424 // with that half. We also bias towards fixing the B half because that
14425 // will more commonly be the high half, and we have to bias one way.
14426 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14427 ArrayRef<int> Inputs) {
14428 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14429 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14430 // Determine whether the free index is in the flipped dword or the
14431 // unflipped dword based on where the pinned index is. We use this bit
14432 // in an xor to conditionally select the adjacent dword.
14433 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14434 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14435 if (IsFixIdxInput == IsFixFreeIdxInput)
14436 FixFreeIdx += 1;
14437 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14438 assert(IsFixIdxInput != IsFixFreeIdxInput &&
14439 "We need to be changing the number of flipped inputs!");
14440 int PSHUFHalfMask[] = {0, 1, 2, 3};
14441 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14442 V = DAG.getNode(
14443 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14444 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14445 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14446
14447 for (int &M : Mask)
14448 if (M >= 0 && M == FixIdx)
14449 M = FixFreeIdx;
14450 else if (M >= 0 && M == FixFreeIdx)
14451 M = FixIdx;
14452 };
14453 if (NumFlippedBToBInputs != 0) {
14454 int BPinnedIdx =
14455 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14456 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14457 } else {
14458 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
14459 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14460 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14461 }
14462 }
14463 }
14464
14465 int PSHUFDMask[] = {0, 1, 2, 3};
14466 PSHUFDMask[ADWord] = BDWord;
14467 PSHUFDMask[BDWord] = ADWord;
14468 V = DAG.getBitcast(
14469 VT,
14470 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14471 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14472
14473 // Adjust the mask to match the new locations of A and B.
14474 for (int &M : Mask)
14475 if (M >= 0 && M/2 == ADWord)
14476 M = 2 * BDWord + M % 2;
14477 else if (M >= 0 && M/2 == BDWord)
14478 M = 2 * ADWord + M % 2;
14479
14480 // Recurse back into this routine to re-compute state now that this isn't
14481 // a 3 and 1 problem.
14482 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14483 };
14484 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14485 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14486 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14487 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14488
14489 // At this point there are at most two inputs to the low and high halves from
14490 // each half. That means the inputs can always be grouped into dwords and
14491 // those dwords can then be moved to the correct half with a dword shuffle.
14492 // We use at most one low and one high word shuffle to collect these paired
14493 // inputs into dwords, and finally a dword shuffle to place them.
14494 int PSHUFLMask[4] = {-1, -1, -1, -1};
14495 int PSHUFHMask[4] = {-1, -1, -1, -1};
14496 int PSHUFDMask[4] = {-1, -1, -1, -1};
14497
14498 // First fix the masks for all the inputs that are staying in their
14499 // original halves. This will then dictate the targets of the cross-half
14500 // shuffles.
14501 auto fixInPlaceInputs =
14502 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14503 MutableArrayRef<int> SourceHalfMask,
14504 MutableArrayRef<int> HalfMask, int HalfOffset) {
14505 if (InPlaceInputs.empty())
14506 return;
14507 if (InPlaceInputs.size() == 1) {
14508 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14509 InPlaceInputs[0] - HalfOffset;
14510 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14511 return;
14512 }
14513 if (IncomingInputs.empty()) {
14514 // Just fix all of the in place inputs.
14515 for (int Input : InPlaceInputs) {
14516 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14517 PSHUFDMask[Input / 2] = Input / 2;
14518 }
14519 return;
14520 }
14521
14522 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
14523 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14524 InPlaceInputs[0] - HalfOffset;
14525 // Put the second input next to the first so that they are packed into
14526 // a dword. We find the adjacent index by toggling the low bit.
14527 int AdjIndex = InPlaceInputs[0] ^ 1;
14528 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14529 llvm::replace(HalfMask, InPlaceInputs[1], AdjIndex);
14530 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14531 };
14532 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14533 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14534
14535 // Now gather the cross-half inputs and place them into a free dword of
14536 // their target half.
14537 // FIXME: This operation could almost certainly be simplified dramatically to
14538 // look more like the 3-1 fixing operation.
14539 auto moveInputsToRightHalf = [&PSHUFDMask](
14540 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14541 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14542 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14543 int DestOffset) {
14544 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14545 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14546 };
14547 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14548 int Word) {
14549 int LowWord = Word & ~1;
14550 int HighWord = Word | 1;
14551 return isWordClobbered(SourceHalfMask, LowWord) ||
14552 isWordClobbered(SourceHalfMask, HighWord);
14553 };
14554
14555 if (IncomingInputs.empty())
14556 return;
14557
14558 if (ExistingInputs.empty()) {
14559 // Map any dwords with inputs from them into the right half.
14560 for (int Input : IncomingInputs) {
14561 // If the source half mask maps over the inputs, turn those into
14562 // swaps and use the swapped lane.
14563 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14564 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14565 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14566 Input - SourceOffset;
14567 // We have to swap the uses in our half mask in one sweep.
14568 for (int &M : HalfMask)
14569 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14570 M = Input;
14571 else if (M == Input)
14572 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14573 } else {
14574 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
14575 Input - SourceOffset &&
14576 "Previous placement doesn't match!");
14577 }
14578 // Note that this correctly re-maps both when we do a swap and when
14579 // we observe the other side of the swap above. We rely on that to
14580 // avoid swapping the members of the input list directly.
14581 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14582 }
14583
14584 // Map the input's dword into the correct half.
14585 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14586 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14587 else
14588 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
14589 Input / 2 &&
14590 "Previous placement doesn't match!");
14591 }
14592
14593 // And just directly shift any other-half mask elements to be same-half
14594 // as we will have mirrored the dword containing the element into the
14595 // same position within that half.
14596 for (int &M : HalfMask)
14597 if (M >= SourceOffset && M < SourceOffset + 4) {
14598 M = M - SourceOffset + DestOffset;
14599 assert(M >= 0 && "This should never wrap below zero!");
14600 }
14601 return;
14602 }
14603
14604 // Ensure we have the input in a viable dword of its current half. This
14605 // is particularly tricky because the original position may be clobbered
14606 // by inputs being moved and *staying* in that half.
14607 if (IncomingInputs.size() == 1) {
14608 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14609 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14610 SourceOffset;
14611 SourceHalfMask[InputFixed - SourceOffset] =
14612 IncomingInputs[0] - SourceOffset;
14613 llvm::replace(HalfMask, IncomingInputs[0], InputFixed);
14614 IncomingInputs[0] = InputFixed;
14615 }
14616 } else if (IncomingInputs.size() == 2) {
14617 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14618 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14619 // We have two non-adjacent or clobbered inputs we need to extract from
14620 // the source half. To do this, we need to map them into some adjacent
14621 // dword slot in the source mask.
14622 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14623 IncomingInputs[1] - SourceOffset};
14624
14625 // If there is a free slot in the source half mask adjacent to one of
14626 // the inputs, place the other input in it. We use (Index XOR 1) to
14627 // compute an adjacent index.
14628 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14629 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14630 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14631 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14632 InputsFixed[1] = InputsFixed[0] ^ 1;
14633 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14634 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14635 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14636 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14637 InputsFixed[0] = InputsFixed[1] ^ 1;
14638 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14639 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14640 // The two inputs are in the same DWord but it is clobbered and the
14641 // adjacent DWord isn't used at all. Move both inputs to the free
14642 // slot.
14643 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14644 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14645 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14646 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14647 } else {
14648 // The only way we hit this point is if there is no clobbering
14649 // (because there are no off-half inputs to this half) and there is no
14650 // free slot adjacent to one of the inputs. In this case, we have to
14651 // swap an input with a non-input.
14652 for (int i = 0; i < 4; ++i)
14653 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14654 "We can't handle any clobbers here!");
14655 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14656 "Cannot have adjacent inputs here!");
14657
14658 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14659 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14660
14661 // We also have to update the final source mask in this case because
14662 // it may need to undo the above swap.
14663 for (int &M : FinalSourceHalfMask)
14664 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14665 M = InputsFixed[1] + SourceOffset;
14666 else if (M == InputsFixed[1] + SourceOffset)
14667 M = (InputsFixed[0] ^ 1) + SourceOffset;
14668
14669 InputsFixed[1] = InputsFixed[0] ^ 1;
14670 }
14671
14672 // Point everything at the fixed inputs.
14673 for (int &M : HalfMask)
14674 if (M == IncomingInputs[0])
14675 M = InputsFixed[0] + SourceOffset;
14676 else if (M == IncomingInputs[1])
14677 M = InputsFixed[1] + SourceOffset;
14678
14679 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14680 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14681 }
14682 } else {
14683 llvm_unreachable("Unhandled input size!");
14684 }
14685
14686 // Now hoist the DWord down to the right half.
14687 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14688 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14689 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14690 for (int &M : HalfMask)
14691 for (int Input : IncomingInputs)
14692 if (M == Input)
14693 M = FreeDWord * 2 + Input % 2;
14694 };
14695 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14696 /*SourceOffset*/ 4, /*DestOffset*/ 0);
14697 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14698 /*SourceOffset*/ 0, /*DestOffset*/ 4);
14699
14700 // Now enact all the shuffles we've computed to move the inputs into their
14701 // target half.
14702 if (!isNoopShuffleMask(PSHUFLMask))
14703 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14704 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14705 if (!isNoopShuffleMask(PSHUFHMask))
14706 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14707 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14708 if (!isNoopShuffleMask(PSHUFDMask))
14709 V = DAG.getBitcast(
14710 VT,
14711 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14712 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14713
14714 // At this point, each half should contain all its inputs, and we can then
14715 // just shuffle them into their final position.
14716 assert(none_of(LoMask, [](int M) { return M >= 4; }) &&
14717 "Failed to lift all the high half inputs to the low mask!");
14718 assert(none_of(HiMask, [](int M) { return M >= 0 && M < 4; }) &&
14719 "Failed to lift all the low half inputs to the high mask!");
14720
14721 // Do a half shuffle for the low mask.
14722 if (!isNoopShuffleMask(LoMask))
14723 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14724 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14725
14726 // Do a half shuffle with the high mask after shifting its values down.
14727 for (int &M : HiMask)
14728 if (M >= 0)
14729 M -= 4;
14730 if (!isNoopShuffleMask(HiMask))
14731 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14732 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14733
14734 return V;
14735}
14736
14737/// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14738/// blend if only one input is used.
14740 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14741 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14743 "Lane crossing shuffle masks not supported");
14744
14745 int NumBytes = VT.getSizeInBits() / 8;
14746 int Size = Mask.size();
14747 int Scale = NumBytes / Size;
14748
14749 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14750 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14751 V1InUse = false;
14752 V2InUse = false;
14753
14754 for (int i = 0; i < NumBytes; ++i) {
14755 int M = Mask[i / Scale];
14756 if (M < 0)
14757 continue;
14758
14759 const int ZeroMask = 0x80;
14760 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14761 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14762 if (Zeroable[i / Scale])
14763 V1Idx = V2Idx = ZeroMask;
14764
14765 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14766 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14767 V1InUse |= (ZeroMask != V1Idx);
14768 V2InUse |= (ZeroMask != V2Idx);
14769 }
14770
14771 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14772 if (V1InUse)
14773 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14774 DAG.getBuildVector(ShufVT, DL, V1Mask));
14775 if (V2InUse)
14776 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14777 DAG.getBuildVector(ShufVT, DL, V2Mask));
14778
14779 // If we need shuffled inputs from both, blend the two.
14780 SDValue V;
14781 if (V1InUse && V2InUse)
14782 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14783 else
14784 V = V1InUse ? V1 : V2;
14785
14786 // Cast the result back to the correct type.
14787 return DAG.getBitcast(VT, V);
14788}
14789
14790/// Generic lowering of 8-lane i16 shuffles.
14791///
14792/// This handles both single-input shuffles and combined shuffle/blends with
14793/// two inputs. The single input shuffles are immediately delegated to
14794/// a dedicated lowering routine.
14795///
14796/// The blends are lowered in one of three fundamental ways. If there are few
14797/// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14798/// of the input is significantly cheaper when lowered as an interleaving of
14799/// the two inputs, try to interleave them. Otherwise, blend the low and high
14800/// halves of the inputs separately (making them have relatively few inputs)
14801/// and then concatenate them.
14803 const APInt &Zeroable, SDValue V1, SDValue V2,
14804 const X86Subtarget &Subtarget,
14805 SelectionDAG &DAG) {
14806 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14807 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14808 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14809
14810 // Whenever we can lower this as a zext, that instruction is strictly faster
14811 // than any alternative.
14812 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14813 Zeroable, Subtarget, DAG))
14814 return ZExt;
14815
14816 // Try to use lower using a truncation.
14817 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14818 Subtarget, DAG))
14819 return V;
14820
14821 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14822
14823 if (NumV2Inputs == 0) {
14824 // Try to use shift instructions.
14825 if (SDValue Shift =
14826 lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
14827 Subtarget, DAG, /*BitwiseOnly*/ false))
14828 return Shift;
14829
14830 // Check for being able to broadcast a single element.
14831 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14832 Mask, Subtarget, DAG))
14833 return Broadcast;
14834
14835 // Try to use bit rotation instructions.
14836 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
14837 Subtarget, DAG))
14838 return Rotate;
14839
14840 // Use dedicated unpack instructions for masks that match their pattern.
14841 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14842 return V;
14843
14844 // Use dedicated pack instructions for masks that match their pattern.
14845 if (SDValue V =
14846 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14847 return V;
14848
14849 // Try to use byte rotation instructions.
14850 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14851 Subtarget, DAG))
14852 return Rotate;
14853
14854 // Make a copy of the mask so it can be modified.
14855 SmallVector<int, 8> MutableMask(Mask);
14856 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14857 Subtarget, DAG);
14858 }
14859
14860 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14861 "All single-input shuffles should be canonicalized to be V1-input "
14862 "shuffles.");
14863
14864 // Try to use shift instructions.
14865 if (SDValue Shift =
14866 lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
14867 DAG, /*BitwiseOnly*/ false))
14868 return Shift;
14869
14870 // See if we can use SSE4A Extraction / Insertion.
14871 if (Subtarget.hasSSE4A())
14872 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14873 Zeroable, DAG))
14874 return V;
14875
14876 // There are special ways we can lower some single-element blends.
14877 if (NumV2Inputs == 1)
14879 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14880 return V;
14881
14882 // We have different paths for blend lowering, but they all must use the
14883 // *exact* same predicate.
14884 bool IsBlendSupported = Subtarget.hasSSE41();
14885 if (IsBlendSupported)
14886 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14887 Zeroable, Subtarget, DAG))
14888 return Blend;
14889
14890 if (SDValue Masked =
14891 lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, Zeroable, DAG))
14892 return Masked;
14893
14894 // Use dedicated unpack instructions for masks that match their pattern.
14895 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14896 return V;
14897
14898 // Use dedicated pack instructions for masks that match their pattern.
14899 if (SDValue V =
14900 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14901 return V;
14902
14903 // Try to use lower using a truncation.
14904 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14905 Subtarget, DAG))
14906 return V;
14907
14908 // Try to use byte rotation instructions.
14909 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14910 Subtarget, DAG))
14911 return Rotate;
14912
14913 if (SDValue BitBlend =
14914 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14915 return BitBlend;
14916
14917 // Try to use byte shift instructions to mask.
14918 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14919 Zeroable, Subtarget, DAG))
14920 return V;
14921
14922 // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
14923 int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
14924 if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
14925 !Subtarget.hasVLX()) {
14926 // Check if this is part of a 256-bit vector truncation.
14927 unsigned PackOpc = 0;
14928 if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
14930 peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
14931 SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
14932 V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
14933 getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
14934 DAG.getTargetConstant(0xEE, DL, MVT::i8));
14935 V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
14936 V1 = extract128BitVector(V1V2, 0, DAG, DL);
14937 V2 = extract128BitVector(V1V2, 4, DAG, DL);
14938 PackOpc = X86ISD::PACKUS;
14939 } else if (Subtarget.hasSSE41()) {
14940 SmallVector<SDValue, 4> DWordClearOps(4,
14941 DAG.getConstant(0, DL, MVT::i32));
14942 for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
14943 DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
14944 SDValue DWordClearMask =
14945 DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
14946 V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
14947 DWordClearMask);
14948 V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
14949 DWordClearMask);
14950 PackOpc = X86ISD::PACKUS;
14951 } else if (!Subtarget.hasSSSE3()) {
14952 SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
14953 V1 = DAG.getBitcast(MVT::v4i32, V1);
14954 V2 = DAG.getBitcast(MVT::v4i32, V2);
14955 V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
14956 V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
14957 V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
14958 V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
14959 PackOpc = X86ISD::PACKSS;
14960 }
14961 if (PackOpc) {
14962 // Now pack things back together.
14963 SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
14964 if (NumEvenDrops == 2) {
14965 Result = DAG.getBitcast(MVT::v4i32, Result);
14966 Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
14967 }
14968 return Result;
14969 }
14970 }
14971
14972 // When compacting odd (upper) elements, use PACKSS pre-SSE41.
14973 int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
14974 if (NumOddDrops == 1) {
14975 bool HasSSE41 = Subtarget.hasSSE41();
14976 V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14977 DAG.getBitcast(MVT::v4i32, V1),
14978 DAG.getTargetConstant(16, DL, MVT::i8));
14979 V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14980 DAG.getBitcast(MVT::v4i32, V2),
14981 DAG.getTargetConstant(16, DL, MVT::i8));
14982 return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
14983 MVT::v8i16, V1, V2);
14984 }
14985
14986 // Try to lower by permuting the inputs into an unpack instruction.
14987 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14988 Mask, Subtarget, DAG))
14989 return Unpack;
14990
14991 // If we can't directly blend but can use PSHUFB, that will be better as it
14992 // can both shuffle and set up the inefficient blend.
14993 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14994 bool V1InUse, V2InUse;
14995 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14996 Zeroable, DAG, V1InUse, V2InUse);
14997 }
14998
14999 // We can always bit-blend if we have to so the fallback strategy is to
15000 // decompose into single-input permutes and blends/unpacks.
15001 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2, Mask,
15002 Zeroable, Subtarget, DAG);
15003}
15004
15005/// Lower 8-lane 16-bit floating point shuffles.
15007 const APInt &Zeroable, SDValue V1, SDValue V2,
15008 const X86Subtarget &Subtarget,
15009 SelectionDAG &DAG) {
15010 assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
15011 assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
15012 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15013 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
15014
15015 if (Subtarget.hasFP16()) {
15016 if (NumV2Elements == 0) {
15017 // Check for being able to broadcast a single element.
15018 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
15019 Mask, Subtarget, DAG))
15020 return Broadcast;
15021 }
15022 if (NumV2Elements == 1 && Mask[0] >= 8)
15024 DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15025 return V;
15026 }
15027
15028 V1 = DAG.getBitcast(MVT::v8i16, V1);
15029 V2 = DAG.getBitcast(MVT::v8i16, V2);
15030 return DAG.getBitcast(MVT::v8f16,
15031 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15032}
15033
15034// Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15035// sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15036// the active subvector is extracted.
15038 ArrayRef<int> OriginalMask, SDValue V1,
15039 SDValue V2, const X86Subtarget &Subtarget,
15040 SelectionDAG &DAG) {
15041 // Commute binary inputs so V2 is a load to simplify VPERMI2/T2 folds.
15042 SmallVector<int, 32> Mask(OriginalMask);
15043 if (!V2.isUndef() && isShuffleFoldableLoad(V1) &&
15044 !isShuffleFoldableLoad(V2)) {
15046 std::swap(V1, V2);
15047 }
15048
15049 MVT MaskVT = VT.changeTypeToInteger();
15050 SDValue MaskNode;
15051 MVT ShuffleVT = VT;
15052 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15053 V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15054 V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15055 ShuffleVT = V1.getSimpleValueType();
15056
15057 // Adjust mask to correct indices for the second input.
15058 int NumElts = VT.getVectorNumElements();
15059 unsigned Scale = 512 / VT.getSizeInBits();
15060 SmallVector<int, 32> AdjustedMask(Mask);
15061 for (int &M : AdjustedMask)
15062 if (NumElts <= M)
15063 M += (Scale - 1) * NumElts;
15064 MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15065 MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15066 } else {
15067 MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15068 }
15069
15070 SDValue Result;
15071 if (V2.isUndef())
15072 Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15073 else
15074 Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15075
15076 if (VT != ShuffleVT)
15077 Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15078
15079 return Result;
15080}
15081
15082/// Generic lowering of v16i8 shuffles.
15083///
15084/// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15085/// detect any complexity reducing interleaving. If that doesn't help, it uses
15086/// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15087/// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15088/// back together.
15090 const APInt &Zeroable, SDValue V1, SDValue V2,
15091 const X86Subtarget &Subtarget,
15092 SelectionDAG &DAG) {
15093 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15094 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15095 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15096
15097 // Try to use shift instructions.
15098 if (SDValue Shift =
15099 lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
15100 DAG, /*BitwiseOnly*/ false))
15101 return Shift;
15102
15103 // Try to use byte rotation instructions.
15104 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15105 Subtarget, DAG))
15106 return Rotate;
15107
15108 // Use dedicated pack instructions for masks that match their pattern.
15109 if (SDValue V =
15110 lowerShuffleWithPACK(DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15111 return V;
15112
15113 // Try to use a zext lowering.
15114 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15115 Zeroable, Subtarget, DAG))
15116 return ZExt;
15117
15118 // Try to use lower using a truncation.
15119 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15120 Subtarget, DAG))
15121 return V;
15122
15123 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15124 Subtarget, DAG))
15125 return V;
15126
15127 // See if we can use SSE4A Extraction / Insertion.
15128 if (Subtarget.hasSSE4A())
15129 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15130 Zeroable, DAG))
15131 return V;
15132
15133 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15134
15135 // For single-input shuffles, there are some nicer lowering tricks we can use.
15136 if (NumV2Elements == 0) {
15137 // Check for being able to broadcast a single element.
15138 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15139 Mask, Subtarget, DAG))
15140 return Broadcast;
15141
15142 // Try to use bit rotation instructions.
15143 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15144 Subtarget, DAG))
15145 return Rotate;
15146
15147 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15148 return V;
15149
15150 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15151 // Notably, this handles splat and partial-splat shuffles more efficiently.
15152 // However, it only makes sense if the pre-duplication shuffle simplifies
15153 // things significantly. Currently, this means we need to be able to
15154 // express the pre-duplication shuffle as an i16 shuffle.
15155 //
15156 // FIXME: We should check for other patterns which can be widened into an
15157 // i16 shuffle as well.
15158 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15159 for (int i = 0; i < 16; i += 2)
15160 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15161 return false;
15162
15163 return true;
15164 };
15165 auto tryToWidenViaDuplication = [&]() -> SDValue {
15166 if (!canWidenViaDuplication(Mask))
15167 return SDValue();
15168 SmallVector<int, 4> LoInputs;
15169 copy_if(Mask, std::back_inserter(LoInputs),
15170 [](int M) { return M >= 0 && M < 8; });
15171 array_pod_sort(LoInputs.begin(), LoInputs.end());
15172 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
15173 SmallVector<int, 4> HiInputs;
15174 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15175 array_pod_sort(HiInputs.begin(), HiInputs.end());
15176 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
15177
15178 bool TargetLo = LoInputs.size() >= HiInputs.size();
15179 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15180 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15181
15182 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15184 for (int I : InPlaceInputs) {
15185 PreDupI16Shuffle[I/2] = I/2;
15186 LaneMap[I] = I;
15187 }
15188 int j = TargetLo ? 0 : 4, je = j + 4;
15189 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15190 // Check if j is already a shuffle of this input. This happens when
15191 // there are two adjacent bytes after we move the low one.
15192 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15193 // If we haven't yet mapped the input, search for a slot into which
15194 // we can map it.
15195 while (j < je && PreDupI16Shuffle[j] >= 0)
15196 ++j;
15197
15198 if (j == je)
15199 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15200 return SDValue();
15201
15202 // Map this input with the i16 shuffle.
15203 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15204 }
15205
15206 // Update the lane map based on the mapping we ended up with.
15207 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15208 }
15209 V1 = DAG.getBitcast(
15210 MVT::v16i8,
15211 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15212 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15213
15214 // Unpack the bytes to form the i16s that will be shuffled into place.
15215 bool EvenInUse = false, OddInUse = false;
15216 for (int i = 0; i < 16; i += 2) {
15217 EvenInUse |= (Mask[i + 0] >= 0);
15218 OddInUse |= (Mask[i + 1] >= 0);
15219 if (EvenInUse && OddInUse)
15220 break;
15221 }
15222 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15223 MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15224 OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15225
15226 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15227 for (int i = 0; i < 16; ++i)
15228 if (Mask[i] >= 0) {
15229 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15230 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
15231 if (PostDupI16Shuffle[i / 2] < 0)
15232 PostDupI16Shuffle[i / 2] = MappedMask;
15233 else
15234 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
15235 "Conflicting entries in the original shuffle!");
15236 }
15237 return DAG.getBitcast(
15238 MVT::v16i8,
15239 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15240 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
15241 };
15242 if (SDValue V = tryToWidenViaDuplication())
15243 return V;
15244 }
15245
15246 if (SDValue Masked =
15247 lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG))
15248 return Masked;
15249
15250 // Use dedicated unpack instructions for masks that match their pattern.
15251 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15252 return V;
15253
15254 // Try to use byte shift instructions to mask.
15255 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15256 Zeroable, Subtarget, DAG))
15257 return V;
15258
15259 // Check for compaction patterns.
15260 bool IsSingleInput = V2.isUndef();
15261 int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
15262
15263 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15264 // with PSHUFB. It is important to do this before we attempt to generate any
15265 // blends but after all of the single-input lowerings. If the single input
15266 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15267 // want to preserve that and we can DAG combine any longer sequences into
15268 // a PSHUFB in the end. But once we start blending from multiple inputs,
15269 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15270 // and there are *very* few patterns that would actually be faster than the
15271 // PSHUFB approach because of its ability to zero lanes.
15272 //
15273 // If the mask is a binary compaction, we can more efficiently perform this
15274 // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15275 //
15276 // FIXME: The only exceptions to the above are blends which are exact
15277 // interleavings with direct instructions supporting them. We currently don't
15278 // handle those well here.
15279 if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15280 bool V1InUse = false;
15281 bool V2InUse = false;
15282
15284 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15285
15286 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15287 // do so. This avoids using them to handle blends-with-zero which is
15288 // important as a single pshufb is significantly faster for that.
15289 if (V1InUse && V2InUse) {
15290 if (Subtarget.hasSSE41())
15291 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15292 Zeroable, Subtarget, DAG))
15293 return Blend;
15294
15295 // We can use an unpack to do the blending rather than an or in some
15296 // cases. Even though the or may be (very minorly) more efficient, we
15297 // preference this lowering because there are common cases where part of
15298 // the complexity of the shuffles goes away when we do the final blend as
15299 // an unpack.
15300 // FIXME: It might be worth trying to detect if the unpack-feeding
15301 // shuffles will both be pshufb, in which case we shouldn't bother with
15302 // this.
15304 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15305 return Unpack;
15306
15307 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
15308 if (Subtarget.hasVBMI())
15309 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
15310 DAG);
15311
15312 // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
15313 if (Subtarget.hasXOP()) {
15314 SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
15315 return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
15316 }
15317
15318 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15319 // PALIGNR will be cheaper than the second PSHUFB+OR.
15321 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15322 return V;
15323 }
15324
15325 return PSHUFB;
15326 }
15327
15328 // There are special ways we can lower some single-element blends.
15329 if (NumV2Elements == 1)
15331 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15332 return V;
15333
15334 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15335 return Blend;
15336
15337 // Check whether a compaction lowering can be done. This handles shuffles
15338 // which take every Nth element for some even N. See the helper function for
15339 // details.
15340 //
15341 // We special case these as they can be particularly efficiently handled with
15342 // the PACKUSB instruction on x86 and they show up in common patterns of
15343 // rearranging bytes to truncate wide elements.
15344 if (NumEvenDrops) {
15345 // NumEvenDrops is the power of two stride of the elements. Another way of
15346 // thinking about it is that we need to drop the even elements this many
15347 // times to get the original input.
15348
15349 // First we need to zero all the dropped bytes.
15350 assert(NumEvenDrops <= 3 &&
15351 "No support for dropping even elements more than 3 times.");
15352 SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15353 for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15354 WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15355 SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15356 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15357 WordClearMask);
15358 if (!IsSingleInput)
15359 V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15360 WordClearMask);
15361
15362 // Now pack things back together.
15363 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15364 IsSingleInput ? V1 : V2);
15365 for (int i = 1; i < NumEvenDrops; ++i) {
15366 Result = DAG.getBitcast(MVT::v8i16, Result);
15367 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15368 }
15369 return Result;
15370 }
15371
15372 int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
15373 if (NumOddDrops == 1) {
15374 V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15375 DAG.getBitcast(MVT::v8i16, V1),
15376 DAG.getTargetConstant(8, DL, MVT::i8));
15377 if (!IsSingleInput)
15378 V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15379 DAG.getBitcast(MVT::v8i16, V2),
15380 DAG.getTargetConstant(8, DL, MVT::i8));
15381 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15382 IsSingleInput ? V1 : V2);
15383 }
15384
15385 // Handle multi-input cases by blending/unpacking single-input shuffles.
15386 if (NumV2Elements > 0)
15387 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
15388 Zeroable, Subtarget, DAG);
15389
15390 // The fallback path for single-input shuffles widens this into two v8i16
15391 // vectors with unpacks, shuffles those, and then pulls them back together
15392 // with a pack.
15393 SDValue V = V1;
15394
15395 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15396 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15397 for (int i = 0; i < 16; ++i)
15398 if (Mask[i] >= 0)
15399 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15400
15401 SDValue VLoHalf, VHiHalf;
15402 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15403 // them out and avoid using UNPCK{L,H} to extract the elements of V as
15404 // i16s.
15405 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15406 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15407 // Use a mask to drop the high bytes.
15408 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15409 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15410 DAG.getConstant(0x00FF, DL, MVT::v8i16));
15411
15412 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15413 VHiHalf = DAG.getUNDEF(MVT::v8i16);
15414
15415 // Squash the masks to point directly into VLoHalf.
15416 for (int &M : LoBlendMask)
15417 if (M >= 0)
15418 M /= 2;
15419 for (int &M : HiBlendMask)
15420 if (M >= 0)
15421 M /= 2;
15422 } else {
15423 // Otherwise just unpack the low half of V into VLoHalf and the high half into
15424 // VHiHalf so that we can blend them as i16s.
15425 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15426
15427 VLoHalf = DAG.getBitcast(
15428 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15429 VHiHalf = DAG.getBitcast(
15430 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15431 }
15432
15433 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15434 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15435
15436 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15437}
15438
15439/// Dispatching routine to lower various 128-bit x86 vector shuffles.
15440///
15441/// This routine breaks down the specific type of 128-bit shuffle and
15442/// dispatches to the lowering routines accordingly.
15444 MVT VT, SDValue V1, SDValue V2,
15445 const APInt &Zeroable,
15446 const X86Subtarget &Subtarget,
15447 SelectionDAG &DAG) {
15448 if (VT == MVT::v8bf16) {
15449 V1 = DAG.getBitcast(MVT::v8i16, V1);
15450 V2 = DAG.getBitcast(MVT::v8i16, V2);
15451 return DAG.getBitcast(VT,
15452 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15453 }
15454
15455 switch (VT.SimpleTy) {
15456 case MVT::v2i64:
15457 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15458 case MVT::v2f64:
15459 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15460 case MVT::v4i32:
15461 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15462 case MVT::v4f32:
15463 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15464 case MVT::v8i16:
15465 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15466 case MVT::v8f16:
15467 return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15468 case MVT::v16i8:
15469 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15470
15471 default:
15472 llvm_unreachable("Unimplemented!");
15473 }
15474}
15475
15476/// Generic routine to split vector shuffle into half-sized shuffles.
15477///
15478/// This routine just extracts two subvectors, shuffles them independently, and
15479/// then concatenates them back together. This should work effectively with all
15480/// AVX vector shuffle types.
15482 SDValue V2, ArrayRef<int> Mask,
15483 SelectionDAG &DAG, bool SimpleOnly) {
15484 assert(VT.getSizeInBits() >= 256 &&
15485 "Only for 256-bit or wider vector shuffles!");
15486 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
15487 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
15488
15489 // If this came from the AVX1 v8i32 -> v8f32 bitcast, split using v4i32.
15490 if (VT == MVT::v8f32) {
15492 SDValue BC2 = peekThroughBitcasts(V2);
15493 if (BC1.getValueType() == MVT::v8i32 && BC2.getValueType() == MVT::v8i32) {
15494 if (SDValue Split = splitAndLowerShuffle(DL, MVT::v8i32, BC1, BC2, Mask,
15495 DAG, SimpleOnly))
15496 return DAG.getBitcast(VT, Split);
15497 }
15498 }
15499
15500 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15501 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15502
15503 int NumElements = VT.getVectorNumElements();
15504 int SplitNumElements = NumElements / 2;
15505 MVT ScalarVT = VT.getVectorElementType();
15506 MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15507
15508 // Use splitVector/extractSubVector so that split build-vectors just build two
15509 // narrower build vectors. This helps shuffling with splats and zeros.
15510 auto SplitVector = [&](SDValue V) {
15511 SDValue LoV, HiV;
15512 std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15513 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15514 DAG.getBitcast(SplitVT, HiV));
15515 };
15516
15517 SDValue LoV1, HiV1, LoV2, HiV2;
15518 std::tie(LoV1, HiV1) = SplitVector(V1);
15519 std::tie(LoV2, HiV2) = SplitVector(V2);
15520
15521 // Now create two 4-way blends of these half-width vectors.
15522 auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
15523 bool &UseHiV1, bool &UseLoV2,
15524 bool &UseHiV2) {
15525 UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
15526 for (int i = 0; i < SplitNumElements; ++i) {
15527 int M = HalfMask[i];
15528 if (M >= NumElements) {
15529 if (M >= NumElements + SplitNumElements)
15530 UseHiV2 = true;
15531 else
15532 UseLoV2 = true;
15533 } else if (M >= 0) {
15534 if (M >= SplitNumElements)
15535 UseHiV1 = true;
15536 else
15537 UseLoV1 = true;
15538 }
15539 }
15540 };
15541
15542 auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
15543 if (!SimpleOnly)
15544 return true;
15545
15546 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15547 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15548
15549 return !(UseHiV1 || UseHiV2);
15550 };
15551
15552 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15553 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15554 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15555 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15556 for (int i = 0; i < SplitNumElements; ++i) {
15557 int M = HalfMask[i];
15558 if (M >= NumElements) {
15559 V2BlendMask[i] = M - NumElements;
15560 BlendMask[i] = SplitNumElements + i;
15561 } else if (M >= 0) {
15562 V1BlendMask[i] = M;
15563 BlendMask[i] = i;
15564 }
15565 }
15566
15567 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15568 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15569
15570 // Because the lowering happens after all combining takes place, we need to
15571 // manually combine these blend masks as much as possible so that we create
15572 // a minimal number of high-level vector shuffle nodes.
15573 assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
15574
15575 // First try just blending the halves of V1 or V2.
15576 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15577 return DAG.getUNDEF(SplitVT);
15578 if (!UseLoV2 && !UseHiV2)
15579 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15580 if (!UseLoV1 && !UseHiV1)
15581 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15582
15583 SDValue V1Blend, V2Blend;
15584 if (UseLoV1 && UseHiV1) {
15585 V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15586 } else {
15587 // We only use half of V1 so map the usage down into the final blend mask.
15588 V1Blend = UseLoV1 ? LoV1 : HiV1;
15589 for (int i = 0; i < SplitNumElements; ++i)
15590 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15591 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15592 }
15593 if (UseLoV2 && UseHiV2) {
15594 V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15595 } else {
15596 // We only use half of V2 so map the usage down into the final blend mask.
15597 V2Blend = UseLoV2 ? LoV2 : HiV2;
15598 for (int i = 0; i < SplitNumElements; ++i)
15599 if (BlendMask[i] >= SplitNumElements)
15600 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15601 }
15602 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15603 };
15604
15605 if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
15606 return SDValue();
15607
15608 SDValue Lo = HalfBlend(LoMask);
15609 SDValue Hi = HalfBlend(HiMask);
15610 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15611}
15612
15613/// Either split a vector in halves or decompose the shuffles and the
15614/// blend/unpack.
15615///
15616/// This is provided as a good fallback for many lowerings of non-single-input
15617/// shuffles with more than one 128-bit lane. In those cases, we want to select
15618/// between splitting the shuffle into 128-bit components and stitching those
15619/// back together vs. extracting the single-input shuffles and blending those
15620/// results.
15622 SDValue V2, ArrayRef<int> Mask,
15623 const APInt &Zeroable,
15624 const X86Subtarget &Subtarget,
15625 SelectionDAG &DAG) {
15626 assert(!V2.isUndef() && "This routine must not be used to lower single-input "
15627 "shuffles as it could then recurse on itself.");
15628 int Size = Mask.size();
15629
15630 // If this can be modeled as a broadcast of two elements followed by a blend,
15631 // prefer that lowering. This is especially important because broadcasts can
15632 // often fold with memory operands.
15633 auto DoBothBroadcast = [&] {
15634 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15635 for (int M : Mask)
15636 if (M >= Size) {
15637 if (V2BroadcastIdx < 0)
15638 V2BroadcastIdx = M - Size;
15639 else if ((M - Size) != V2BroadcastIdx &&
15640 !IsElementEquivalent(Size, V2, V2, M - Size, V2BroadcastIdx))
15641 return false;
15642 } else if (M >= 0) {
15643 if (V1BroadcastIdx < 0)
15644 V1BroadcastIdx = M;
15645 else if (M != V1BroadcastIdx &&
15646 !IsElementEquivalent(Size, V1, V1, M, V1BroadcastIdx))
15647 return false;
15648 }
15649 return true;
15650 };
15651 if (DoBothBroadcast())
15652 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15653 Subtarget, DAG);
15654
15655 // If the inputs all stem from a single 128-bit lane of each input, then we
15656 // split them rather than blending because the split will decompose to
15657 // unusually few instructions.
15658 int LaneCount = VT.getSizeInBits() / 128;
15659 int LaneSize = Size / LaneCount;
15660 SmallBitVector LaneInputs[2];
15661 LaneInputs[0].resize(LaneCount, false);
15662 LaneInputs[1].resize(LaneCount, false);
15663 for (int i = 0; i < Size; ++i)
15664 if (Mask[i] >= 0)
15665 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15666 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15667 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15668 /*SimpleOnly*/ false);
15669
15670 // Without AVX2, if we can freely split the subvectors then we're better off
15671 // performing half width shuffles.
15672 if (!Subtarget.hasAVX2()) {
15674 SDValue BC2 = peekThroughBitcasts(V2);
15675 bool SplatOrSplitV1 = isFreeToSplitVector(BC1, DAG) ||
15676 DAG.isSplatValue(BC1, /*AllowUndefs=*/true);
15677 bool SplatOrSplitV2 = isFreeToSplitVector(BC2, DAG) ||
15678 DAG.isSplatValue(BC2, /*AllowUndefs=*/true);
15679 if (SplatOrSplitV1 && SplatOrSplitV2)
15680 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15681 /*SimpleOnly*/ false);
15682 }
15683
15684 // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
15685 // requires that the decomposed single-input shuffles don't end up here.
15686 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15687 Subtarget, DAG);
15688}
15689
15690// Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15691// TODO: Extend to support v8f32 (+ 512-bit shuffles).
15693 SDValue V1, SDValue V2,
15694 ArrayRef<int> Mask,
15695 SelectionDAG &DAG) {
15696 assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
15697
15698 int LHSMask[4] = {-1, -1, -1, -1};
15699 int RHSMask[4] = {-1, -1, -1, -1};
15700 int SHUFPDMask[4] = {-1, -1, -1, -1};
15701
15702 // As SHUFPD uses a single LHS/RHS element per lane, we can always
15703 // perform the shuffle once the lanes have been shuffled in place.
15704 for (int i = 0; i != 4; ++i) {
15705 int M = Mask[i];
15706 if (M < 0)
15707 continue;
15708 int LaneBase = i & ~1;
15709 auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15710 LaneMask[LaneBase + (M & 1)] = M;
15711 SHUFPDMask[i] = M & 1;
15712 }
15713
15714 SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15715 SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15716 return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15717 getSHUFPDImmForMask(SHUFPDMask, DL, DAG));
15718}
15719
15720/// Lower a vector shuffle crossing multiple 128-bit lanes as
15721/// a lane permutation followed by a per-lane permutation.
15722///
15723/// This is mainly for cases where we can have non-repeating permutes
15724/// in each lane.
15725///
15726/// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15727/// we should investigate merging them.
15729 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15730 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15731 int NumElts = VT.getVectorNumElements();
15732 int NumLanes = VT.getSizeInBits() / 128;
15733 int NumEltsPerLane = NumElts / NumLanes;
15734 bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
15735
15736 /// Attempts to find a sublane permute with the given size
15737 /// that gets all elements into their target lanes.
15738 ///
15739 /// Returns a decomposed shuffle, or an empty SDValue if none is found.
15740 /// SameMask is set to true when the cross-lane mask reproduces Mask. Callers
15741 /// must then stop trying smaller sublane sizes to avoid a legalization cycle.
15742 auto getSublanePermute = [&](int NumSublanes, bool &SameMask) -> SDValue {
15743 int NumSublanesPerLane = NumSublanes / NumLanes;
15744 int NumEltsPerSublane = NumElts / NumSublanes;
15745
15746 SmallVector<int, 16> CrossLaneMask;
15747 SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
15748 // CrossLaneMask but one entry == one sublane.
15749 SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
15750 APInt DemandedCrossLane = APInt::getZero(NumElts);
15751
15752 for (int i = 0; i != NumElts; ++i) {
15753 int M = Mask[i];
15754 if (M < 0)
15755 continue;
15756
15757 int SrcSublane = M / NumEltsPerSublane;
15758 int DstLane = i / NumEltsPerLane;
15759
15760 // We only need to get the elements into the right lane, not sublane.
15761 // So search all sublanes that make up the destination lane.
15762 bool Found = false;
15763 int DstSubStart = DstLane * NumSublanesPerLane;
15764 int DstSubEnd = DstSubStart + NumSublanesPerLane;
15765 for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
15766 if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
15767 continue;
15768
15769 Found = true;
15770 CrossLaneMaskLarge[DstSublane] = SrcSublane;
15771 int DstSublaneOffset = DstSublane * NumEltsPerSublane;
15772 InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
15773 DemandedCrossLane.setBit(InLaneMask[i]);
15774 break;
15775 }
15776 if (!Found)
15777 return SDValue();
15778 }
15779
15780 // Fill CrossLaneMask using CrossLaneMaskLarge.
15781 narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15782
15783 if (!CanUseSublanes) {
15784 // If we're only shuffling a single lowest lane and the rest are identity
15785 // then don't bother.
15786 // TODO - isShuffleMaskInputInPlace could be extended to something like
15787 // this.
15788 int NumIdentityLanes = 0;
15789 bool OnlyShuffleLowestLane = true;
15790 for (int i = 0; i != NumLanes; ++i) {
15791 int LaneOffset = i * NumEltsPerLane;
15792 if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15793 i * NumEltsPerLane))
15794 NumIdentityLanes++;
15795 else if (CrossLaneMask[LaneOffset] != 0)
15796 OnlyShuffleLowestLane = false;
15797 }
15798 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15799 return SDValue();
15800 }
15801
15802 // Simplify CrossLaneMask based on the actual demanded elements.
15803 if (V1.hasOneUse())
15804 for (int i = 0; i != NumElts; ++i)
15805 if (!DemandedCrossLane[i])
15806 CrossLaneMask[i] = SM_SentinelUndef;
15807
15808 // Avoid returning the same shuffle operation. For example,
15809 // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
15810 // undef:v16i16
15811 if (CrossLaneMask == Mask) {
15812 // Trying another sublane size could bring us back to this shuffle,
15813 // causing an infinite loop during legalization.
15814 SameMask = true;
15815 return SDValue();
15816 }
15817 if (InLaneMask == Mask)
15818 return SDValue();
15819
15820 SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15821 return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15822 InLaneMask);
15823 };
15824
15825 // Try 128-bit lanes first. If that fails, try 64-bit and then 32-bit
15826 // sublanes, if supported.
15827 int MaxSublaneScale = 1;
15828 if (CanUseSublanes)
15829 MaxSublaneScale = Subtarget.hasFastVariableCrossLaneShuffle() ? 4 : 2;
15830
15831 for (int SublaneScale = 1; SublaneScale <= MaxSublaneScale;
15832 SublaneScale *= 2) {
15833 bool SameMask = false;
15834 if (SDValue V = getSublanePermute(
15835 /*NumSublanes=*/NumLanes * SublaneScale, SameMask))
15836 return V;
15837 if (SameMask)
15838 return SDValue();
15839 }
15840 return SDValue();
15841}
15842
15843/// Helper to get compute inlane shuffle mask for a complete shuffle mask.
15844static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
15845 SmallVector<int> &InLaneMask) {
15846 int Size = Mask.size();
15847 InLaneMask.assign(Mask.begin(), Mask.end());
15848 for (int i = 0; i < Size; ++i) {
15849 int &M = InLaneMask[i];
15850 if (M < 0)
15851 continue;
15852 if (((M % Size) / LaneSize) != (i / LaneSize))
15853 M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15854 }
15855}
15856
15857/// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15858/// source with a lane permutation.
15859///
15860/// This lowering strategy results in four instructions in the worst case for a
15861/// single-input cross lane shuffle which is lower than any other fully general
15862/// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15863/// shuffle pattern should be handled prior to trying this lowering.
15865 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15866 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15867 // FIXME: This should probably be generalized for 512-bit vectors as well.
15868 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15869 int Size = Mask.size();
15870 int LaneSize = Size / 2;
15871
15872 // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15873 // Only do this if the elements aren't all from the lower lane,
15874 // otherwise we're (probably) better off doing a split.
15875 if (VT == MVT::v4f64 &&
15876 !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15877 return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
15878
15879 // If there are only inputs from one 128-bit lane, splitting will in fact be
15880 // less expensive. The flags track whether the given lane contains an element
15881 // that crosses to another lane.
15882 bool AllLanes;
15883 if (!Subtarget.hasAVX2()) {
15884 bool LaneCrossing[2] = {false, false};
15885 for (int i = 0; i < Size; ++i)
15886 if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15887 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15888 AllLanes = LaneCrossing[0] && LaneCrossing[1];
15889 } else {
15890 bool LaneUsed[2] = {false, false};
15891 for (int i = 0; i < Size; ++i)
15892 if (Mask[i] >= 0)
15893 LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15894 AllLanes = LaneUsed[0] && LaneUsed[1];
15895 }
15896
15897 // TODO - we could support shuffling V2 in the Flipped input.
15898 assert(V2.isUndef() &&
15899 "This last part of this routine only works on single input shuffles");
15900
15901 SmallVector<int> InLaneMask;
15902 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
15903
15904 assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15905 "In-lane shuffle mask expected");
15906
15907 // If we're not using both lanes in each lane and the inlane mask is not
15908 // repeating, then we're better off splitting.
15909 if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
15910 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15911 /*SimpleOnly*/ false);
15912
15913 // Flip the lanes, and shuffle the results which should now be in-lane.
15914 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15915 SDValue Flipped = DAG.getBitcast(PVT, V1);
15916 Flipped =
15917 DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15918 Flipped = DAG.getBitcast(VT, Flipped);
15919 return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15920}
15921
15922/// Handle lowering 2-lane 128-bit shuffles.
15924 SDValue V2, ArrayRef<int> Mask,
15925 const APInt &Zeroable,
15926 const X86Subtarget &Subtarget,
15927 SelectionDAG &DAG) {
15928 if (V2.isUndef()) {
15929 // Attempt to match VBROADCAST*128 subvector broadcast load.
15930 bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
15931 bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
15932 if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
15934 MVT MemVT = VT.getHalfNumVectorElementsVT();
15935 unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
15937 if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
15938 VT, MemVT, Ld, Ofs, DAG))
15939 return BcstLd;
15940 }
15941
15942 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15943 if (Subtarget.hasAVX2())
15944 return SDValue();
15945 }
15946
15947 bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15948
15949 SmallVector<int, 4> WidenedMask;
15950 if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15951 return SDValue();
15952
15953 bool IsLowZero = (Zeroable & 0x3) == 0x3;
15954 bool IsHighZero = (Zeroable & 0xc) == 0xc;
15955
15956 // Try to use an insert into a zero vector.
15957 if (WidenedMask[0] == 0 && IsHighZero) {
15958 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15959 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15960 DAG.getVectorIdxConstant(0, DL));
15961 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15962 getZeroVector(VT, Subtarget, DAG, DL), LoV,
15963 DAG.getVectorIdxConstant(0, DL));
15964 }
15965
15966 // TODO: If minimizing size and one of the inputs is a zero vector and the
15967 // the zero vector has only one use, we could use a VPERM2X128 to save the
15968 // instruction bytes needed to explicitly generate the zero vector.
15969
15970 // Blends are faster and handle all the non-lane-crossing cases.
15971 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15972 Subtarget, DAG))
15973 return Blend;
15974
15975 // If either input operand is a zero vector, use VPERM2X128 because its mask
15976 // allows us to replace the zero input with an implicit zero.
15977 if (!IsLowZero && !IsHighZero) {
15978 // Check for patterns which can be matched with a single insert of a 128-bit
15979 // subvector.
15980 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
15981 if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
15982
15983 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15984 // this will likely become vinsertf128 which can't fold a 256-bit memop.
15986 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15987 SDValue SubVec =
15988 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
15989 DAG.getVectorIdxConstant(0, DL));
15990 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15991 DAG.getVectorIdxConstant(2, DL));
15992 }
15993 }
15994
15995 // Try to use SHUF128 if possible.
15996 if (Subtarget.hasVLX()) {
15997 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15998 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15999 ((WidenedMask[1] % 2) << 1);
16000 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
16001 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16002 }
16003 }
16004 }
16005
16006 // Otherwise form a 128-bit permutation. After accounting for undefs,
16007 // convert the 64-bit shuffle mask selection values into 128-bit
16008 // selection bits by dividing the indexes by 2 and shifting into positions
16009 // defined by a vperm2*128 instruction's immediate control byte.
16010
16011 // The immediate permute control byte looks like this:
16012 // [1:0] - select 128 bits from sources for low half of destination
16013 // [2] - ignore
16014 // [3] - zero low half of destination
16015 // [5:4] - select 128 bits from sources for high half of destination
16016 // [6] - ignore
16017 // [7] - zero high half of destination
16018
16019 assert((WidenedMask[0] >= 0 || IsLowZero) &&
16020 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
16021
16022 unsigned PermMask = 0;
16023 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
16024 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
16025
16026 // Check the immediate mask and replace unused sources with undef.
16027 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
16028 V1 = DAG.getUNDEF(VT);
16029 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
16030 V2 = DAG.getUNDEF(VT);
16031
16032 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16033 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16034}
16035
16036/// Lower a vector shuffle by first fixing the 128-bit lanes and then
16037/// shuffling each lane.
16038///
16039/// This attempts to create a repeated lane shuffle where each lane uses one
16040/// or two of the lanes of the inputs. The lanes of the input vectors are
16041/// shuffled in one or two independent shuffles to get the lanes into the
16042/// position needed by the final shuffle.
16044 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16045 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16046 // This is only useful for binary shuffle with a non-repeating mask.
16047 if (V2.isUndef() || is128BitLaneRepeatedShuffleMask(VT, Mask))
16048 return SDValue();
16049
16050 int NumElts = Mask.size();
16051 int NumLanes = VT.getSizeInBits() / 128;
16052 int NumLaneElts = 128 / VT.getScalarSizeInBits();
16053 SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16054 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16055
16056 // First pass will try to fill in the RepeatMask from lanes that need two
16057 // sources.
16058 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16059 int Srcs[2] = {-1, -1};
16060 SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16061 for (int i = 0; i != NumLaneElts; ++i) {
16062 int M = Mask[(Lane * NumLaneElts) + i];
16063 if (M < 0)
16064 continue;
16065 // Determine which of the possible input lanes (NumLanes from each source)
16066 // this element comes from. Assign that as one of the sources for this
16067 // lane. We can assign up to 2 sources for this lane. If we run out
16068 // sources we can't do anything.
16069 int LaneSrc = M / NumLaneElts;
16070 int Src;
16071 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16072 Src = 0;
16073 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16074 Src = 1;
16075 else
16076 return SDValue();
16077
16078 Srcs[Src] = LaneSrc;
16079 InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16080 }
16081
16082 // If this lane has two sources, see if it fits with the repeat mask so far.
16083 if (Srcs[1] < 0)
16084 continue;
16085
16086 LaneSrcs[Lane][0] = Srcs[0];
16087 LaneSrcs[Lane][1] = Srcs[1];
16088
16089 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16090 assert(M1.size() == M2.size() && "Unexpected mask size");
16091 for (int i = 0, e = M1.size(); i != e; ++i)
16092 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16093 return false;
16094 return true;
16095 };
16096
16097 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16098 assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
16099 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16100 int M = Mask[i];
16101 if (M < 0)
16102 continue;
16103 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
16104 "Unexpected mask element");
16105 MergedMask[i] = M;
16106 }
16107 };
16108
16109 if (MatchMasks(InLaneMask, RepeatMask)) {
16110 // Merge this lane mask into the final repeat mask.
16111 MergeMasks(InLaneMask, RepeatMask);
16112 continue;
16113 }
16114
16115 // Didn't find a match. Swap the operands and try again.
16116 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16118
16119 if (MatchMasks(InLaneMask, RepeatMask)) {
16120 // Merge this lane mask into the final repeat mask.
16121 MergeMasks(InLaneMask, RepeatMask);
16122 continue;
16123 }
16124
16125 // Couldn't find a match with the operands in either order.
16126 return SDValue();
16127 }
16128
16129 // Now handle any lanes with only one source.
16130 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16131 // If this lane has already been processed, skip it.
16132 if (LaneSrcs[Lane][0] >= 0)
16133 continue;
16134
16135 for (int i = 0; i != NumLaneElts; ++i) {
16136 int M = Mask[(Lane * NumLaneElts) + i];
16137 if (M < 0)
16138 continue;
16139
16140 // If RepeatMask isn't defined yet we can define it ourself.
16141 if (RepeatMask[i] < 0)
16142 RepeatMask[i] = M % NumLaneElts;
16143
16144 if (RepeatMask[i] < NumElts) {
16145 if (RepeatMask[i] != M % NumLaneElts)
16146 return SDValue();
16147 LaneSrcs[Lane][0] = M / NumLaneElts;
16148 } else {
16149 if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16150 return SDValue();
16151 LaneSrcs[Lane][1] = M / NumLaneElts;
16152 }
16153 }
16154
16155 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16156 return SDValue();
16157 }
16158
16159 SmallVector<int, 16> NewMask(NumElts, -1);
16160 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16161 int Src = LaneSrcs[Lane][0];
16162 for (int i = 0; i != NumLaneElts; ++i) {
16163 int M = -1;
16164 if (Src >= 0)
16165 M = Src * NumLaneElts + i;
16166 NewMask[Lane * NumLaneElts + i] = M;
16167 }
16168 }
16169 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16170 // Ensure we didn't get back the shuffle we started with.
16171 // FIXME: This is a hack to make up for some splat handling code in
16172 // getVectorShuffle.
16173 if (isa<ShuffleVectorSDNode>(NewV1) &&
16174 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16175 return SDValue();
16176
16177 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16178 int Src = LaneSrcs[Lane][1];
16179 for (int i = 0; i != NumLaneElts; ++i) {
16180 int M = -1;
16181 if (Src >= 0)
16182 M = Src * NumLaneElts + i;
16183 NewMask[Lane * NumLaneElts + i] = M;
16184 }
16185 }
16186 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16187 // Ensure we didn't get back the shuffle we started with.
16188 // FIXME: This is a hack to make up for some splat handling code in
16189 // getVectorShuffle.
16190 if (isa<ShuffleVectorSDNode>(NewV2) &&
16191 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16192 return SDValue();
16193
16194 for (int i = 0; i != NumElts; ++i) {
16195 if (Mask[i] < 0) {
16196 NewMask[i] = -1;
16197 continue;
16198 }
16199 NewMask[i] = RepeatMask[i % NumLaneElts];
16200 if (NewMask[i] < 0)
16201 continue;
16202
16203 NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16204 }
16205 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16206}
16207
16208/// If the input shuffle mask results in a vector that is undefined in all upper
16209/// or lower half elements and that mask accesses only 2 halves of the
16210/// shuffle's operands, return true. A mask of half the width with mask indexes
16211/// adjusted to access the extracted halves of the original shuffle operands is
16212/// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16213/// lower half of each input operand is accessed.
16214static bool
16216 int &HalfIdx1, int &HalfIdx2) {
16217 assert((Mask.size() == HalfMask.size() * 2) &&
16218 "Expected input mask to be twice as long as output");
16219
16220 // Exactly one half of the result must be undef to allow narrowing.
16221 bool UndefLower = isUndefLowerHalf(Mask);
16222 bool UndefUpper = isUndefUpperHalf(Mask);
16223 if (UndefLower == UndefUpper)
16224 return false;
16225
16226 unsigned HalfNumElts = HalfMask.size();
16227 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16228 HalfIdx1 = -1;
16229 HalfIdx2 = -1;
16230 for (unsigned i = 0; i != HalfNumElts; ++i) {
16231 int M = Mask[i + MaskIndexOffset];
16232 if (M < 0) {
16233 HalfMask[i] = M;
16234 continue;
16235 }
16236
16237 // Determine which of the 4 half vectors this element is from.
16238 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16239 int HalfIdx = M / HalfNumElts;
16240
16241 // Determine the element index into its half vector source.
16242 int HalfElt = M % HalfNumElts;
16243
16244 // We can shuffle with up to 2 half vectors, set the new 'half'
16245 // shuffle mask accordingly.
16246 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16247 HalfMask[i] = HalfElt;
16248 HalfIdx1 = HalfIdx;
16249 continue;
16250 }
16251 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16252 HalfMask[i] = HalfElt + HalfNumElts;
16253 HalfIdx2 = HalfIdx;
16254 continue;
16255 }
16256
16257 // Too many half vectors referenced.
16258 return false;
16259 }
16260
16261 return true;
16262}
16263
16264/// Given the output values from getHalfShuffleMask(), create a half width
16265/// shuffle of extracted vectors followed by an insert back to full width.
16267 ArrayRef<int> HalfMask, int HalfIdx1,
16268 int HalfIdx2, bool UndefLower,
16269 SelectionDAG &DAG, bool UseConcat = false) {
16270 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
16271 assert(V1.getValueType().isSimple() && "Expecting only simple types");
16272
16273 MVT VT = V1.getSimpleValueType();
16274 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16275 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16276
16277 auto getHalfVector = [&](int HalfIdx) {
16278 if (HalfIdx < 0)
16279 return DAG.getUNDEF(HalfVT);
16280 SDValue V = (HalfIdx < 2 ? V1 : V2);
16281 HalfIdx = (HalfIdx % 2) * HalfNumElts;
16282 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16283 DAG.getVectorIdxConstant(HalfIdx, DL));
16284 };
16285
16286 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16287 SDValue Half1 = getHalfVector(HalfIdx1);
16288 SDValue Half2 = getHalfVector(HalfIdx2);
16289 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16290 if (UseConcat) {
16291 SDValue Op0 = V;
16292 SDValue Op1 = DAG.getUNDEF(HalfVT);
16293 if (UndefLower)
16294 std::swap(Op0, Op1);
16295 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16296 }
16297
16298 unsigned Offset = UndefLower ? HalfNumElts : 0;
16299 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16301}
16302
16303/// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16304/// This allows for fast cases such as subvector extraction/insertion
16305/// or shuffling smaller vector types which can lower more efficiently.
16307 SDValue V2, ArrayRef<int> Mask,
16308 const X86Subtarget &Subtarget,
16309 SelectionDAG &DAG) {
16310 assert((VT.is256BitVector() || VT.is512BitVector()) &&
16311 "Expected 256-bit or 512-bit vector");
16312
16313 bool UndefLower = isUndefLowerHalf(Mask);
16314 if (!UndefLower && !isUndefUpperHalf(Mask))
16315 return SDValue();
16316
16317 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
16318 "Completely undef shuffle mask should have been simplified already");
16319
16320 // Upper half is undef and lower half is whole upper subvector.
16321 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16322 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16323 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16324 if (!UndefLower &&
16325 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16326 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16327 DAG.getVectorIdxConstant(HalfNumElts, DL));
16328 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16329 DAG.getVectorIdxConstant(0, DL));
16330 }
16331
16332 // Lower half is undef and upper half is whole lower subvector.
16333 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16334 if (UndefLower &&
16335 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16336 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16337 DAG.getVectorIdxConstant(0, DL));
16338 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16339 DAG.getVectorIdxConstant(HalfNumElts, DL));
16340 }
16341
16342 int HalfIdx1, HalfIdx2;
16343 SmallVector<int, 8> HalfMask(HalfNumElts);
16344 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
16345 return SDValue();
16346
16347 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
16348
16349 // Only shuffle the halves of the inputs when useful.
16350 unsigned NumLowerHalves =
16351 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
16352 unsigned NumUpperHalves =
16353 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
16354 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
16355
16356 // Determine the larger pattern of undef/halves, then decide if it's worth
16357 // splitting the shuffle based on subtarget capabilities and types.
16358 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
16359 if (!UndefLower) {
16360 // XXXXuuuu: no insert is needed.
16361 // Always extract lowers when setting lower - these are all free subreg ops.
16362 if (NumUpperHalves == 0)
16363 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16364 UndefLower, DAG);
16365
16366 if (NumUpperHalves == 1) {
16367 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
16368 if (Subtarget.hasAVX2()) {
16369 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
16370 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
16371 !is128BitUnpackShuffleMask(HalfMask, DAG) &&
16372 (!isSingleSHUFPSMask(HalfMask) ||
16373 Subtarget.hasFastVariableCrossLaneShuffle()))
16374 return SDValue();
16375 // If this is an unary shuffle (assume that the 2nd operand is
16376 // canonicalized to undef), then we can use vpermpd. Otherwise, we
16377 // are better off extracting the upper half of 1 operand and using a
16378 // narrow shuffle.
16379 if (EltWidth == 64 && V2.isUndef())
16380 return SDValue();
16381 // If this is an unary vXi8 shuffle with inplace halves, then perform as
16382 // full width pshufb, and then merge.
16383 if (EltWidth == 8 && HalfIdx1 == 0 && HalfIdx2 == 1)
16384 return SDValue();
16385 }
16386 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16387 if (Subtarget.hasAVX512() && VT.is512BitVector())
16388 return SDValue();
16389 // Extract + narrow shuffle is better than the wide alternative.
16390 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16391 UndefLower, DAG);
16392 }
16393
16394 // Don't extract both uppers, instead shuffle and then extract.
16395 assert(NumUpperHalves == 2 && "Half vector count went wrong");
16396 return SDValue();
16397 }
16398
16399 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
16400 if (NumUpperHalves == 0) {
16401 // AVX2 has efficient 64-bit element cross-lane shuffles.
16402 // TODO: Refine to account for unary shuffle, splat, and other masks?
16403 if (Subtarget.hasAVX2() && EltWidth == 64)
16404 return SDValue();
16405 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16406 if (Subtarget.hasAVX512() && VT.is512BitVector())
16407 return SDValue();
16408 // Narrow shuffle + insert is better than the wide alternative.
16409 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16410 UndefLower, DAG);
16411 }
16412
16413 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
16414 return SDValue();
16415}
16416
16417/// Handle case where shuffle sources are coming from the same 128-bit lane and
16418/// every lane can be represented as the same repeating mask - allowing us to
16419/// shuffle the sources with the repeating shuffle and then permute the result
16420/// to the destination lanes.
16422 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16423 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16424 int NumElts = VT.getVectorNumElements();
16425 int NumLanes = VT.getSizeInBits() / 128;
16426 int NumLaneElts = NumElts / NumLanes;
16427
16428 // On AVX2 we may be able to just shuffle the lowest elements and then
16429 // broadcast the result.
16430 if (Subtarget.hasAVX2()) {
16431 for (unsigned BroadcastSize : {16, 32, 64}) {
16432 if (BroadcastSize <= VT.getScalarSizeInBits())
16433 continue;
16434 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16435
16436 // Attempt to match a repeating pattern every NumBroadcastElts,
16437 // accounting for UNDEFs but only references the lowest 128-bit
16438 // lane of the inputs.
16439 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16440 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16441 for (int j = 0; j != NumBroadcastElts; ++j) {
16442 int M = Mask[i + j];
16443 if (M < 0)
16444 continue;
16445 int &R = RepeatMask[j];
16446 if (0 != ((M % NumElts) / NumLaneElts))
16447 return false;
16448 if (0 <= R && R != M)
16449 return false;
16450 R = M;
16451 }
16452 return true;
16453 };
16454
16455 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16456 if (!FindRepeatingBroadcastMask(RepeatMask))
16457 continue;
16458
16459 // Shuffle the (lowest) repeated elements in place for broadcast.
16460 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16461
16462 // Shuffle the actual broadcast.
16463 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16464 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16465 for (int j = 0; j != NumBroadcastElts; ++j)
16466 BroadcastMask[i + j] = j;
16467
16468 // Avoid returning the same shuffle operation. For example,
16469 // v8i32 = vector_shuffle<0,1,0,1,0,1,0,1> t5, undef:v8i32
16470 if (BroadcastMask == Mask)
16471 return SDValue();
16472
16473 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16474 BroadcastMask);
16475 }
16476 }
16477
16478 // Bail if the shuffle mask doesn't cross 128-bit lanes.
16479 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16480 return SDValue();
16481
16482 // Bail if we already have a repeated lane shuffle mask.
16483 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16484 return SDValue();
16485
16486 // Helper to look for repeated mask in each split sublane, and that those
16487 // sublanes can then be permuted into place.
16488 auto ShuffleSubLanes = [&](int SubLaneScale) {
16489 int NumSubLanes = NumLanes * SubLaneScale;
16490 int NumSubLaneElts = NumLaneElts / SubLaneScale;
16491
16492 // Check that all the sources are coming from the same lane and see if we
16493 // can form a repeating shuffle mask (local to each sub-lane). At the same
16494 // time, determine the source sub-lane for each destination sub-lane.
16495 int TopSrcSubLane = -1;
16496 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16497 SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
16498 SubLaneScale,
16499 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
16500
16501 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16502 // Extract the sub-lane mask, check that it all comes from the same lane
16503 // and normalize the mask entries to come from the first lane.
16504 int SrcLane = -1;
16505 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16506 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16507 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16508 if (M < 0)
16509 continue;
16510 int Lane = (M % NumElts) / NumLaneElts;
16511 if ((0 <= SrcLane) && (SrcLane != Lane))
16512 return SDValue();
16513 SrcLane = Lane;
16514 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16515 SubLaneMask[Elt] = LocalM;
16516 }
16517
16518 // Whole sub-lane is UNDEF.
16519 if (SrcLane < 0)
16520 continue;
16521
16522 // Attempt to match against the candidate repeated sub-lane masks.
16523 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16524 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16525 for (int i = 0; i != NumSubLaneElts; ++i) {
16526 if (M1[i] < 0 || M2[i] < 0)
16527 continue;
16528 if (M1[i] != M2[i])
16529 return false;
16530 }
16531 return true;
16532 };
16533
16534 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16535 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16536 continue;
16537
16538 // Merge the sub-lane mask into the matching repeated sub-lane mask.
16539 for (int i = 0; i != NumSubLaneElts; ++i) {
16540 int M = SubLaneMask[i];
16541 if (M < 0)
16542 continue;
16543 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
16544 "Unexpected mask element");
16545 RepeatedSubLaneMask[i] = M;
16546 }
16547
16548 // Track the top most source sub-lane - by setting the remaining to
16549 // UNDEF we can greatly simplify shuffle matching.
16550 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16551 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16552 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16553 break;
16554 }
16555
16556 // Bail if we failed to find a matching repeated sub-lane mask.
16557 if (Dst2SrcSubLanes[DstSubLane] < 0)
16558 return SDValue();
16559 }
16560 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
16561 "Unexpected source lane");
16562
16563 // Create a repeating shuffle mask for the entire vector.
16564 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16565 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16566 int Lane = SubLane / SubLaneScale;
16567 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16568 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16569 int M = RepeatedSubLaneMask[Elt];
16570 if (M < 0)
16571 continue;
16572 int Idx = (SubLane * NumSubLaneElts) + Elt;
16573 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16574 }
16575 }
16576
16577 // Shuffle each source sub-lane to its destination.
16578 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16579 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16580 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16581 if (SrcSubLane < 0)
16582 continue;
16583 for (int j = 0; j != NumSubLaneElts; ++j)
16584 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16585 }
16586
16587 // Avoid returning the same shuffle operation.
16588 // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
16589 if (RepeatedMask == Mask || SubLaneMask == Mask)
16590 return SDValue();
16591
16592 SDValue RepeatedShuffle =
16593 DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16594
16595 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16596 SubLaneMask);
16597 };
16598
16599 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16600 // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
16601 // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
16602 // Otherwise we can only permute whole 128-bit lanes.
16603 int MinSubLaneScale = 1, MaxSubLaneScale = 1;
16604 if (Subtarget.hasAVX2() && VT.is256BitVector()) {
16605 bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
16606 MinSubLaneScale = 2;
16607 MaxSubLaneScale =
16608 (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
16609 }
16610 if (Subtarget.hasBWI() && VT == MVT::v64i8)
16611 MinSubLaneScale = MaxSubLaneScale = 4;
16612
16613 for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
16614 if (SDValue Shuffle = ShuffleSubLanes(Scale))
16615 return Shuffle;
16616
16617 return SDValue();
16618}
16619
16621 bool &ForceV1Zero, bool &ForceV2Zero,
16622 unsigned &ShuffleImm, ArrayRef<int> Mask,
16623 const APInt &Zeroable) {
16624 int NumElts = VT.getVectorNumElements();
16625 assert(VT.getScalarSizeInBits() == 64 &&
16626 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
16627 "Unexpected data type for VSHUFPD");
16628 assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
16629 "Illegal shuffle mask");
16630
16631 bool ZeroLane[2] = { true, true };
16632 for (int i = 0; i < NumElts; ++i)
16633 ZeroLane[i & 1] &= Zeroable[i];
16634
16635 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
16636 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
16637 bool IsSHUFPD = true;
16638 bool IsCommutable = true;
16639 SmallVector<int, 8> SHUFPDMask(NumElts, -1);
16640 for (int i = 0; i < NumElts; ++i) {
16641 if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16642 continue;
16643 if (Mask[i] < 0)
16644 return false;
16645 int Val = (i & 6) + NumElts * (i & 1);
16646 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16647 if (Mask[i] < Val || Mask[i] > Val + 1)
16648 IsSHUFPD = false;
16649 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16650 IsCommutable = false;
16651 SHUFPDMask[i] = Mask[i] % 2;
16652 }
16653
16654 if (!IsSHUFPD && !IsCommutable)
16655 return false;
16656
16657 if (!IsSHUFPD && IsCommutable)
16658 std::swap(V1, V2);
16659
16660 ForceV1Zero = ZeroLane[0];
16661 ForceV2Zero = ZeroLane[1];
16662 ShuffleImm = getSHUFPDImm(SHUFPDMask);
16663 return true;
16664}
16665
16667 SDValue V2, ArrayRef<int> Mask,
16668 const APInt &Zeroable,
16669 const X86Subtarget &Subtarget,
16670 SelectionDAG &DAG) {
16671 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
16672 "Unexpected data type for VSHUFPD");
16673
16674 unsigned Immediate = 0;
16675 bool ForceV1Zero = false, ForceV2Zero = false;
16676 if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16677 Mask, Zeroable))
16678 return SDValue();
16679
16680 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16681 if (ForceV1Zero)
16682 V1 = getZeroVector(VT, Subtarget, DAG, DL);
16683 if (ForceV2Zero)
16684 V2 = getZeroVector(VT, Subtarget, DAG, DL);
16685
16686 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16687 DAG.getTargetConstant(Immediate, DL, MVT::i8));
16688}
16689
16690// Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16691// by zeroable elements in the remaining 24 elements. Turn this into two
16692// vmovqb instructions shuffled together.
16694 SDValue V1, SDValue V2,
16695 ArrayRef<int> Mask,
16696 const APInt &Zeroable,
16697 SelectionDAG &DAG) {
16698 assert(VT == MVT::v32i8 && "Unexpected type!");
16699
16700 // The first 8 indices should be every 8th element.
16701 if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16702 return SDValue();
16703
16704 // Remaining elements need to be zeroable.
16705 if (Zeroable.countl_one() < (Mask.size() - 8))
16706 return SDValue();
16707
16708 V1 = DAG.getBitcast(MVT::v4i64, V1);
16709 V2 = DAG.getBitcast(MVT::v4i64, V2);
16710
16711 V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16712 V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16713
16714 // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16715 // the upper bits of the result using an unpckldq.
16716 SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16717 { 0, 1, 2, 3, 16, 17, 18, 19,
16718 4, 5, 6, 7, 20, 21, 22, 23 });
16719 // Insert the unpckldq into a zero vector to widen to v32i8.
16720 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16721 DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16722 DAG.getVectorIdxConstant(0, DL));
16723}
16724
16725// a = shuffle v1, v2, mask1 ; interleaving lower lanes of v1 and v2
16726// b = shuffle v1, v2, mask2 ; interleaving higher lanes of v1 and v2
16727// =>
16728// ul = unpckl v1, v2
16729// uh = unpckh v1, v2
16730// a = vperm ul, uh
16731// b = vperm ul, uh
16732//
16733// Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
16734// and permute. We cannot directly match v3 because it is split into two
16735// 256-bit vectors in earlier isel stages. Therefore, this function matches a
16736// pair of 256-bit shuffles and makes sure the masks are consecutive.
16737//
16738// Once unpck and permute nodes are created, the permute corresponding to this
16739// shuffle is returned, while the other permute replaces the other half of the
16740// shuffle in the selection dag.
16742 SDValue V1, SDValue V2,
16743 ArrayRef<int> Mask,
16744 SelectionDAG &DAG) {
16745 if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
16746 VT != MVT::v32i8)
16747 return SDValue();
16748 // <B0, B1, B0+1, B1+1, ..., >
16749 auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
16750 unsigned Begin1) {
16751 size_t Size = Mask.size();
16752 assert(Size % 2 == 0 && "Expected even mask size");
16753 for (unsigned I = 0; I < Size; I += 2) {
16754 if (Mask[I] != (int)(Begin0 + I / 2) ||
16755 Mask[I + 1] != (int)(Begin1 + I / 2))
16756 return false;
16757 }
16758 return true;
16759 };
16760 // Check which half is this shuffle node
16761 int NumElts = VT.getVectorNumElements();
16762 size_t FirstQtr = NumElts / 2;
16763 size_t ThirdQtr = NumElts + NumElts / 2;
16764 bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
16765 bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
16766 if (!IsFirstHalf && !IsSecondHalf)
16767 return SDValue();
16768
16769 // Find the intersection between shuffle users of V1 and V2.
16770 SmallVector<SDNode *, 2> Shuffles;
16771 for (SDNode *User : V1->users())
16772 if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
16773 User->getOperand(1) == V2)
16774 Shuffles.push_back(User);
16775 // Limit user size to two for now.
16776 if (Shuffles.size() != 2)
16777 return SDValue();
16778 // Find out which half of the 512-bit shuffles is each smaller shuffle
16779 auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
16780 auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
16781 SDNode *FirstHalf;
16782 SDNode *SecondHalf;
16783 if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
16784 IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
16785 FirstHalf = Shuffles[0];
16786 SecondHalf = Shuffles[1];
16787 } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
16788 IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
16789 FirstHalf = Shuffles[1];
16790 SecondHalf = Shuffles[0];
16791 } else {
16792 return SDValue();
16793 }
16794 // Lower into unpck and perm. Return the perm of this shuffle and replace
16795 // the other.
16796 SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
16797 SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
16798 SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16799 DAG.getTargetConstant(0x20, DL, MVT::i8));
16800 SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16801 DAG.getTargetConstant(0x31, DL, MVT::i8));
16802 if (IsFirstHalf) {
16803 DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
16804 return Perm1;
16805 }
16806 DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
16807 return Perm2;
16808}
16809
16810/// Handle lowering of 4-lane 64-bit floating point shuffles.
16811///
16812/// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16813/// isn't available.
16815 const APInt &Zeroable, SDValue V1, SDValue V2,
16816 const X86Subtarget &Subtarget,
16817 SelectionDAG &DAG) {
16818 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16819 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16820 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16821
16822 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16823 Subtarget, DAG))
16824 return V;
16825
16826 if (V2.isUndef()) {
16827 // Check for being able to broadcast a single element.
16828 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16829 Mask, Subtarget, DAG))
16830 return Broadcast;
16831
16832 // Use low duplicate instructions for masks that match their pattern.
16833 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16834 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16835
16836 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16837 // Non-half-crossing single input shuffles can be lowered with an
16838 // interleaved permutation.
16839 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16840 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16841 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16842 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16843 }
16844
16845 // With AVX2 we have direct support for this permutation.
16846 if (Subtarget.hasAVX2())
16847 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16848 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16849
16850 // Try to create an in-lane repeating shuffle mask and then shuffle the
16851 // results into the target lanes.
16853 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16854 return V;
16855
16856 // Try to permute the lanes and then use a per-lane permute.
16857 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16858 Mask, DAG, Subtarget))
16859 return V;
16860
16861 // Otherwise, fall back.
16862 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16863 DAG, Subtarget);
16864 }
16865
16866 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16867 Zeroable, Subtarget, DAG))
16868 return Blend;
16869
16870 // Use dedicated unpack instructions for masks that match their pattern.
16871 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, V1, V2, Mask, DAG))
16872 return V;
16873
16874 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16875 Zeroable, Subtarget, DAG))
16876 return Op;
16877
16878 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16879 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16880 bool V1IsSplat = isShuffleMaskInputBroadcastable(0, Mask);
16881 bool V2IsSplat = isShuffleMaskInputBroadcastable(1, Mask);
16882
16883 // If we have lane crossing shuffles AND they don't all come from the lower
16884 // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16885 // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16886 // canonicalize to a blend of splat which isn't necessary for this combine.
16887 if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16888 !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16889 (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16890 (V2.getOpcode() != ISD::BUILD_VECTOR) &&
16891 (!Subtarget.hasAVX2() ||
16892 !((V1IsInPlace || V1IsSplat) && (V2IsInPlace || V2IsSplat))))
16893 return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
16894
16895 // If we have one input in place, then we can permute the other input and
16896 // blend the result.
16897 if (V1IsInPlace || V2IsInPlace)
16898 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16899 Zeroable, Subtarget, DAG);
16900
16901 // Try to create an in-lane repeating shuffle mask and then shuffle the
16902 // results into the target lanes.
16904 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16905 return V;
16906
16907 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16908 // shuffle. However, if we have AVX2 and either inputs are already in place,
16909 // we will be able to shuffle even across lanes the other input in a single
16910 // instruction so skip this pattern.
16911 if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
16913 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16914 return V;
16915
16916 // If we have VLX support, we can use VEXPAND.
16917 if (Subtarget.hasVLX())
16918 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4f64, V1, V2, Mask,
16919 Zeroable, Subtarget, DAG))
16920 return V;
16921
16922 // If we have AVX2 then we always want to lower with a blend because an v4 we
16923 // can fully permute the elements.
16924 if (Subtarget.hasAVX2())
16925 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16926 Zeroable, Subtarget, DAG);
16927
16928 // Otherwise fall back on generic lowering.
16929 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16930 Subtarget, DAG);
16931}
16932
16933/// Handle lowering of 4-lane 64-bit integer shuffles.
16934///
16935/// This routine is only called when we have AVX2 and thus a reasonable
16936/// instruction set for v4i64 shuffling..
16938 const APInt &Zeroable, SDValue V1, SDValue V2,
16939 const X86Subtarget &Subtarget,
16940 SelectionDAG &DAG) {
16941 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16942 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16943 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16944 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16945
16946 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16947 Subtarget, DAG))
16948 return V;
16949
16950 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16951 Zeroable, Subtarget, DAG))
16952 return Blend;
16953
16954 // Check for being able to broadcast a single element.
16955 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16956 Subtarget, DAG))
16957 return Broadcast;
16958
16959 // Try to use shift instructions if fast.
16960 if (Subtarget.preferLowerShuffleAsShift())
16961 if (SDValue Shift =
16962 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16963 Subtarget, DAG, /*BitwiseOnly*/ true))
16964 return Shift;
16965
16966 if (V2.isUndef()) {
16967 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16968 // can use lower latency instructions that will operate on both lanes.
16969 SmallVector<int, 2> RepeatedMask;
16970 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16971 SmallVector<int, 4> PSHUFDMask;
16972 narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16973 return DAG.getBitcast(
16974 MVT::v4i64,
16975 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16976 DAG.getBitcast(MVT::v8i32, V1),
16977 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16978 }
16979
16980 // AVX2 provides a direct instruction for permuting a single input across
16981 // lanes.
16982 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16983 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16984 }
16985
16986 // Try to use shift instructions.
16987 if (SDValue Shift =
16988 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
16989 DAG, /*BitwiseOnly*/ false))
16990 return Shift;
16991
16992 // If we have VLX support, we can use VALIGN or VEXPAND.
16993 if (Subtarget.hasVLX()) {
16994 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16995 Zeroable, Subtarget, DAG))
16996 return Rotate;
16997
16998 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4i64, V1, V2, Mask,
16999 Zeroable, Subtarget, DAG))
17000 return V;
17001 }
17002
17003 // Try to use PALIGNR.
17004 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
17005 Subtarget, DAG))
17006 return Rotate;
17007
17008 // Use dedicated unpack instructions for masks that match their pattern.
17009 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, V1, V2, Mask, DAG))
17010 return V;
17011
17012 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
17013 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
17014
17015 // If we have one input in place, then we can permute the other input and
17016 // blend the result.
17017 if (V1IsInPlace || V2IsInPlace)
17018 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17019 Zeroable, Subtarget, DAG);
17020
17021 // Try to create an in-lane repeating shuffle mask and then shuffle the
17022 // results into the target lanes.
17024 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17025 return V;
17026
17027 // Try to lower to PERMQ(BLENDD(V1,V2)).
17028 if (SDValue V =
17029 lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
17030 return V;
17031
17032 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17033 // shuffle. However, if we have AVX2 and either inputs are already in place,
17034 // we will be able to shuffle even across lanes the other input in a single
17035 // instruction so skip this pattern.
17036 if (!V1IsInPlace && !V2IsInPlace)
17038 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17039 return Result;
17040
17041 // Otherwise fall back on generic blend lowering.
17042 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17043 Zeroable, Subtarget, DAG);
17044}
17045
17046/// Handle lowering of 8-lane 32-bit floating point shuffles.
17047///
17048/// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17049/// isn't available.
17051 const APInt &Zeroable, SDValue V1, SDValue V2,
17052 const X86Subtarget &Subtarget,
17053 SelectionDAG &DAG) {
17054 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17055 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17056 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17057
17058 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17059 Zeroable, Subtarget, DAG))
17060 return Blend;
17061
17062 // Check for being able to broadcast a single element.
17063 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17064 Subtarget, DAG))
17065 return Broadcast;
17066
17067 if (!Subtarget.hasAVX2()) {
17068 SmallVector<int> InLaneMask;
17069 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
17070
17071 if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
17072 if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
17073 /*SimpleOnly*/ true))
17074 return R;
17075 }
17076 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17077 Zeroable, Subtarget, DAG))
17078 return DAG.getBitcast(MVT::v8f32, ZExt);
17079
17080 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17081 // options to efficiently lower the shuffle.
17082 SmallVector<int, 4> RepeatedMask;
17083 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17084 assert(RepeatedMask.size() == 4 &&
17085 "Repeated masks must be half the mask width!");
17086
17087 // Use even/odd duplicate instructions for masks that match their pattern.
17088 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17089 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17090 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17091 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17092
17093 if (V2.isUndef())
17094 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17095 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17096
17097 // Use dedicated unpack instructions for masks that match their pattern.
17098 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, V1, V2, Mask, DAG))
17099 return V;
17100
17101 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
17102 // have already handled any direct blends.
17103 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
17104 }
17105
17106 // Try to create an in-lane repeating shuffle mask and then shuffle the
17107 // results into the target lanes.
17109 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17110 return V;
17111
17112 // If we have a single input shuffle with different shuffle patterns in the
17113 // two 128-bit lanes use the variable mask to VPERMILPS.
17114 if (V2.isUndef()) {
17115 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
17116 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17117 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
17118 }
17119 if (Subtarget.hasAVX2()) {
17120 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17121 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17122 }
17123 // Otherwise, fall back.
17124 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17125 DAG, Subtarget);
17126 }
17127
17128 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17129 // shuffle.
17131 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17132 return Result;
17133
17134 // If we have VLX support, we can use VEXPAND.
17135 if (Subtarget.hasVLX())
17136 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f32, V1, V2, Mask,
17137 Zeroable, Subtarget, DAG))
17138 return V;
17139
17140 // Try to match an interleave of two v8f32s and lower them as unpck and
17141 // permutes using ymms. This needs to go before we try to split the vectors.
17142 // Don't attempt on AVX1 if we're likely to split vectors anyway.
17143 if ((Subtarget.hasAVX2() ||
17146 !Subtarget.hasAVX512())
17147 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
17148 Mask, DAG))
17149 return V;
17150
17151 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17152 // since after split we get a more efficient code using vpunpcklwd and
17153 // vpunpckhwd instrs than vblend.
17154 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
17155 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17156 Subtarget, DAG);
17157
17158 // If we have AVX2 then we always want to lower with a blend because at v8 we
17159 // can fully permute the elements.
17160 if (Subtarget.hasAVX2())
17161 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17162 Zeroable, Subtarget, DAG);
17163
17164 // Otherwise fall back on generic lowering.
17165 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17166 Subtarget, DAG);
17167}
17168
17169/// Handle lowering of 8-lane 32-bit integer shuffles.
17170///
17171/// This routine is only called when we have AVX2 and thus a reasonable
17172/// instruction set for v8i32 shuffling..
17174 const APInt &Zeroable, SDValue V1, SDValue V2,
17175 const X86Subtarget &Subtarget,
17176 SelectionDAG &DAG) {
17177 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17178 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17179 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17180 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
17181
17182 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
17183
17184 // Whenever we can lower this as a zext, that instruction is strictly faster
17185 // than any alternative. It also allows us to fold memory operands into the
17186 // shuffle in many cases.
17187 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17188 Zeroable, Subtarget, DAG))
17189 return ZExt;
17190
17191 // Try to match an interleave of two v8i32s and lower them as unpck and
17192 // permutes using ymms. This needs to go before we try to split the vectors.
17193 if (!Subtarget.hasAVX512())
17194 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
17195 Mask, DAG))
17196 return V;
17197
17198 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17199 // since after split we get a more efficient code than vblend by using
17200 // vpunpcklwd and vpunpckhwd instrs.
17201 if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
17202 !Subtarget.hasAVX512())
17203 return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17204 Subtarget, DAG);
17205
17206 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17207 Zeroable, Subtarget, DAG))
17208 return Blend;
17209
17210 // Check for being able to broadcast a single element.
17211 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17212 Subtarget, DAG))
17213 return Broadcast;
17214
17215 // Try to use shift instructions if fast.
17216 if (Subtarget.preferLowerShuffleAsShift()) {
17217 if (SDValue Shift =
17218 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17219 Subtarget, DAG, /*BitwiseOnly*/ true))
17220 return Shift;
17221 if (NumV2Elements == 0)
17222 if (SDValue Rotate =
17223 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17224 return Rotate;
17225 }
17226
17227 // If the shuffle mask is repeated in each 128-bit lane we can use more
17228 // efficient instructions that mirror the shuffles across the two 128-bit
17229 // lanes.
17230 SmallVector<int, 4> RepeatedMask;
17231 bool Is128BitLaneRepeatedShuffle =
17232 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17233 if (Is128BitLaneRepeatedShuffle) {
17234 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17235 if (V2.isUndef())
17236 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17237 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17238
17239 // Use dedicated unpack instructions for masks that match their pattern.
17240 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, V1, V2, Mask, DAG))
17241 return V;
17242 }
17243
17244 // Try to use shift instructions.
17245 if (SDValue Shift =
17246 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
17247 DAG, /*BitwiseOnly*/ false))
17248 return Shift;
17249
17250 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
17251 if (SDValue Rotate =
17252 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17253 return Rotate;
17254
17255 // If we have VLX support, we can use VALIGN or EXPAND.
17256 if (Subtarget.hasVLX()) {
17257 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17258 Zeroable, Subtarget, DAG))
17259 return Rotate;
17260
17261 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i32, V1, V2, Mask,
17262 Zeroable, Subtarget, DAG))
17263 return V;
17264 }
17265
17266 // Try to use byte rotation instructions.
17267 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17268 Subtarget, DAG))
17269 return Rotate;
17270
17271 // Try to create an in-lane repeating shuffle mask and then shuffle the
17272 // results into the target lanes.
17274 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17275 return V;
17276
17277 if (V2.isUndef()) {
17278 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17279 // because that should be faster than the variable permute alternatives.
17280 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, V1, V2, Mask, DAG))
17281 return V;
17282
17283 // If the shuffle patterns aren't repeated but it's a single input, directly
17284 // generate a cross-lane VPERMD instruction.
17285 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17286 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17287 }
17288
17289 // Assume that a single SHUFPS is faster than an alternative sequence of
17290 // multiple instructions (even if the CPU has a domain penalty).
17291 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17292 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17293 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17294 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17295 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17296 CastV1, CastV2, DAG);
17297 return DAG.getBitcast(MVT::v8i32, ShufPS);
17298 }
17299
17300 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17301 // shuffle.
17303 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17304 return Result;
17305
17306 // Otherwise fall back on generic blend lowering.
17307 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17308 Zeroable, Subtarget, DAG);
17309}
17310
17311/// Handle lowering of 16-lane 16-bit integer shuffles.
17312///
17313/// This routine is only called when we have AVX2 and thus a reasonable
17314/// instruction set for v16i16 shuffling..
17316 const APInt &Zeroable, SDValue V1, SDValue V2,
17317 const X86Subtarget &Subtarget,
17318 SelectionDAG &DAG) {
17319 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17320 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17321 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17322 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
17323
17324 // Whenever we can lower this as a zext, that instruction is strictly faster
17325 // than any alternative. It also allows us to fold memory operands into the
17326 // shuffle in many cases.
17328 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17329 return ZExt;
17330
17331 // Check for being able to broadcast a single element.
17332 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17333 Subtarget, DAG))
17334 return Broadcast;
17335
17336 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17337 Zeroable, Subtarget, DAG))
17338 return Blend;
17339
17340 // Use dedicated unpack instructions for masks that match their pattern.
17341 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, V1, V2, Mask, DAG))
17342 return V;
17343
17344 // Use dedicated pack instructions for masks that match their pattern.
17345 if (SDValue V =
17346 lowerShuffleWithPACK(DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17347 return V;
17348
17349 // Try to use lower using a truncation.
17350 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17351 Subtarget, DAG))
17352 return V;
17353
17354 // Try to use shift instructions.
17355 if (SDValue Shift =
17356 lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17357 Subtarget, DAG, /*BitwiseOnly*/ false))
17358 return Shift;
17359
17360 // Try to use byte rotation instructions.
17361 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17362 Subtarget, DAG))
17363 return Rotate;
17364
17365 // Try to create an in-lane repeating shuffle mask and then shuffle the
17366 // results into the target lanes.
17368 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17369 return V;
17370
17371 if (V2.isUndef()) {
17372 // Try to use bit rotation instructions.
17373 if (SDValue Rotate =
17374 lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17375 return Rotate;
17376
17377 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17378 // because that should be faster than the variable permute alternatives.
17379 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, V1, V2, Mask, DAG))
17380 return V;
17381
17382 // There are no generalized cross-lane shuffle operations available on i16
17383 // element types.
17384 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17386 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17387 return V;
17388
17389 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17390 DAG, Subtarget);
17391 }
17392
17393 SmallVector<int, 8> RepeatedMask;
17394 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17395 // As this is a single-input shuffle, the repeated mask should be
17396 // a strictly valid v8i16 mask that we can pass through to the v8i16
17397 // lowering to handle even the v16 case.
17399 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17400 }
17401 }
17402
17403 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17404 Zeroable, Subtarget, DAG))
17405 return PSHUFB;
17406
17407 // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17408 if (Subtarget.hasBWI())
17409 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17410
17411 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17412 // shuffle.
17414 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17415 return Result;
17416
17417 // Try to permute the lanes and then use a per-lane permute.
17419 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17420 return V;
17421
17422 // Try to match an interleave of two v16i16s and lower them as unpck and
17423 // permutes using ymms.
17424 if (!Subtarget.hasAVX512())
17425 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
17426 Mask, DAG))
17427 return V;
17428
17429 // Otherwise fall back on generic lowering.
17430 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17431 Subtarget, DAG);
17432}
17433
17434/// Handle lowering of 32-lane 8-bit integer shuffles.
17435///
17436/// This routine is only called when we have AVX2 and thus a reasonable
17437/// instruction set for v32i8 shuffling..
17439 const APInt &Zeroable, SDValue V1, SDValue V2,
17440 const X86Subtarget &Subtarget,
17441 SelectionDAG &DAG) {
17442 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17443 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17444 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17445 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
17446
17447 // Whenever we can lower this as a zext, that instruction is strictly faster
17448 // than any alternative. It also allows us to fold memory operands into the
17449 // shuffle in many cases.
17450 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17451 Zeroable, Subtarget, DAG))
17452 return ZExt;
17453
17454 // Check for being able to broadcast a single element.
17455 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17456 Subtarget, DAG))
17457 return Broadcast;
17458
17459 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17460 Zeroable, Subtarget, DAG))
17461 return Blend;
17462
17463 // Use dedicated unpack instructions for masks that match their pattern.
17464 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, V1, V2, Mask, DAG))
17465 return V;
17466
17467 // Use dedicated pack instructions for masks that match their pattern.
17468 if (SDValue V =
17469 lowerShuffleWithPACK(DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17470 return V;
17471
17472 // Try to use lower using a truncation.
17473 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17474 Subtarget, DAG))
17475 return V;
17476
17477 // Try to use shift instructions.
17478 if (SDValue Shift =
17479 lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
17480 DAG, /*BitwiseOnly*/ false))
17481 return Shift;
17482
17483 // Try to use byte rotation instructions.
17484 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17485 Subtarget, DAG))
17486 return Rotate;
17487
17488 // Try to use bit rotation instructions.
17489 if (V2.isUndef())
17490 if (SDValue Rotate =
17491 lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17492 return Rotate;
17493
17494 // Try to create an in-lane repeating shuffle mask and then shuffle the
17495 // results into the target lanes.
17497 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17498 return V;
17499
17500 // There are no generalized cross-lane shuffle operations available on i8
17501 // element types.
17502 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17503 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17504 // because that should be faster than the variable permute alternatives.
17505 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, V1, V2, Mask, DAG))
17506 return V;
17507
17509 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17510 return V;
17511
17512 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17513 DAG, Subtarget);
17514 }
17515
17516 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17517 Zeroable, Subtarget, DAG))
17518 return PSHUFB;
17519
17520 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17521 if (Subtarget.hasVBMI())
17522 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17523
17524 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17525 // shuffle.
17527 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17528 return Result;
17529
17530 // Try to permute the lanes and then use a per-lane permute.
17532 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17533 return V;
17534
17535 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17536 // by zeroable elements in the remaining 24 elements. Turn this into two
17537 // vmovqb instructions shuffled together.
17538 if (Subtarget.hasVLX())
17539 if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
17540 Mask, Zeroable, DAG))
17541 return V;
17542
17543 // Try to match an interleave of two v32i8s and lower them as unpck and
17544 // permutes using ymms.
17545 if (!Subtarget.hasAVX512())
17546 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
17547 Mask, DAG))
17548 return V;
17549
17550 // Otherwise fall back on generic lowering.
17551 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17552 Subtarget, DAG);
17553}
17554
17555/// High-level routine to lower various 256-bit x86 vector shuffles.
17556///
17557/// This routine either breaks down the specific type of a 256-bit x86 vector
17558/// shuffle or splits it into two 128-bit shuffles and fuses the results back
17559/// together based on the available instructions.
17561 SDValue V1, SDValue V2, const APInt &Zeroable,
17562 const X86Subtarget &Subtarget,
17563 SelectionDAG &DAG) {
17564 // If we have a single input to the zero element, insert that into V1 if we
17565 // can do so cheaply.
17566 int NumElts = VT.getVectorNumElements();
17567 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17568
17569 if (NumV2Elements == 1 && Mask[0] >= NumElts)
17571 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17572 return Insertion;
17573
17574 // Handle special cases where the lower or upper half is UNDEF.
17575 if (SDValue V =
17576 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17577 return V;
17578
17579 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
17580 // can check for those subtargets here and avoid much of the subtarget
17581 // querying in the per-vector-type lowering routines. With AVX1 we have
17582 // essentially *zero* ability to manipulate a 256-bit vector with integer
17583 // types. Since we'll use floating point types there eventually, just
17584 // immediately cast everything to a float and operate entirely in that domain.
17585 if (VT.isInteger() && !Subtarget.hasAVX2()) {
17586 int ElementBits = VT.getScalarSizeInBits();
17587 if (ElementBits < 32) {
17588 // No floating point type available, if we can't use the bit operations
17589 // for masking/blending then decompose into 128-bit vectors.
17590 if (SDValue V =
17591 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
17592 return V;
17593 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17594 return V;
17595 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17596 }
17597
17598 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
17600 V1 = DAG.getBitcast(FpVT, V1);
17601 V2 = DAG.getBitcast(FpVT, V2);
17602 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
17603 }
17604
17605 if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
17606 V1 = DAG.getBitcast(MVT::v16i16, V1);
17607 V2 = DAG.getBitcast(MVT::v16i16, V2);
17608 return DAG.getBitcast(VT,
17609 DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
17610 }
17611
17612 switch (VT.SimpleTy) {
17613 case MVT::v4f64:
17614 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17615 case MVT::v4i64:
17616 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17617 case MVT::v8f32:
17618 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17619 case MVT::v8i32:
17620 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17621 case MVT::v16i16:
17622 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17623 case MVT::v32i8:
17624 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17625
17626 default:
17627 llvm_unreachable("Not a valid 256-bit x86 vector type!");
17628 }
17629}
17630
17631/// Try to lower a vector shuffle as a 128-bit shuffles.
17633 const APInt &Zeroable, SDValue V1, SDValue V2,
17634 const X86Subtarget &Subtarget,
17635 SelectionDAG &DAG) {
17636 assert(VT.getScalarSizeInBits() == 64 &&
17637 "Unexpected element type size for 128bit shuffle.");
17638
17639 // To handle 256 bit vector requires VLX and most probably
17640 // function lowerV2X128VectorShuffle() is better solution.
17641 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
17642
17643 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17644 SmallVector<int, 4> Widened128Mask;
17645 if (!canWidenShuffleElements(Mask, Widened128Mask))
17646 return SDValue();
17647 assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
17648
17649 // Try to use an insert into a zero vector.
17650 if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17651 (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17652 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17653 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17654 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17655 DAG.getVectorIdxConstant(0, DL));
17656 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17657 getZeroVector(VT, Subtarget, DAG, DL), LoV,
17658 DAG.getVectorIdxConstant(0, DL));
17659 }
17660
17661 // Check for patterns which can be matched with a single insert of a 256-bit
17662 // subvector.
17663 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
17664 if (OnlyUsesV1 ||
17665 isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
17666 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17667 SDValue SubVec =
17668 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17669 DAG.getVectorIdxConstant(0, DL));
17670 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17671 DAG.getVectorIdxConstant(4, DL));
17672 }
17673
17674 // See if this is an insertion of the lower 128-bits of V2 into V1.
17675 bool IsInsert = true;
17676 int V2Index = -1;
17677 for (int i = 0; i < 4; ++i) {
17678 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17679 if (Widened128Mask[i] < 0)
17680 continue;
17681
17682 // Make sure all V1 subvectors are in place.
17683 if (Widened128Mask[i] < 4) {
17684 if (Widened128Mask[i] != i) {
17685 IsInsert = false;
17686 break;
17687 }
17688 } else {
17689 // Make sure we only have a single V2 index and its the lowest 128-bits.
17690 if (V2Index >= 0 || Widened128Mask[i] != 4) {
17691 IsInsert = false;
17692 break;
17693 }
17694 V2Index = i;
17695 }
17696 }
17697 if (IsInsert && V2Index >= 0) {
17698 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17699 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17700 DAG.getVectorIdxConstant(0, DL));
17701 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17702 }
17703
17704 // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17705 // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17706 // possible we at least ensure the lanes stay sequential to help later
17707 // combines.
17708 SmallVector<int, 2> Widened256Mask;
17709 if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17710 Widened128Mask.clear();
17711 narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17712 }
17713
17714 // Try to lower to vshuf64x2/vshuf32x4.
17715 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17716 int PermMask[4] = {-1, -1, -1, -1};
17717 // Ensure elements came from the same Op.
17718 for (int i = 0; i < 4; ++i) {
17719 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17720 if (Widened128Mask[i] < 0)
17721 continue;
17722
17723 SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17724 unsigned OpIndex = i / 2;
17725 if (Ops[OpIndex].isUndef())
17726 Ops[OpIndex] = Op;
17727 else if (Ops[OpIndex] != Op)
17728 return SDValue();
17729
17730 PermMask[i] = Widened128Mask[i] % 4;
17731 }
17732
17733 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17734 getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
17735}
17736
17737/// Handle lowering of 8-lane 64-bit floating point shuffles.
17739 const APInt &Zeroable, SDValue V1, SDValue V2,
17740 const X86Subtarget &Subtarget,
17741 SelectionDAG &DAG) {
17742 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17743 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17744 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17745
17746 if (V2.isUndef()) {
17747 // Use low duplicate instructions for masks that match their pattern.
17748 if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
17749 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17750
17751 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17752 // Non-half-crossing single input shuffles can be lowered with an
17753 // interleaved permutation.
17754 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17755 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17756 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17757 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17758 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17759 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17760 }
17761
17762 SmallVector<int, 4> RepeatedMask;
17763 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17764 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17765 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17766 }
17767
17768 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17769 V2, Subtarget, DAG))
17770 return Shuf128;
17771
17772 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, V1, V2, Mask, DAG))
17773 return Unpck;
17774
17775 // Check if the blend happens to exactly fit that of SHUFPD.
17776 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17777 Zeroable, Subtarget, DAG))
17778 return Op;
17779
17780 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f64, V1, V2, Mask, Zeroable,
17781 Subtarget, DAG))
17782 return V;
17783
17784 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17785 Zeroable, Subtarget, DAG))
17786 return Blend;
17787
17788 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPD which
17789 // requires an extra register for the index vector; VALIGNQ uses an immediate.
17790 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8f64, V1, V2, Mask,
17791 Zeroable, Subtarget, DAG))
17792 return Rotate;
17793
17794 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17795}
17796
17797/// Handle lowering of 16-lane 32-bit floating point shuffles.
17799 const APInt &Zeroable, SDValue V1, SDValue V2,
17800 const X86Subtarget &Subtarget,
17801 SelectionDAG &DAG) {
17802 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17803 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17804 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17805
17806 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17807 // options to efficiently lower the shuffle.
17808 SmallVector<int, 4> RepeatedMask;
17809 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17810 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17811
17812 // Use even/odd duplicate instructions for masks that match their pattern.
17813 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17814 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17815 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17816 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17817
17818 if (V2.isUndef())
17819 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17820 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17821
17822 // Use dedicated unpack instructions for masks that match their pattern.
17823 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, V1, V2, Mask, DAG))
17824 return V;
17825
17826 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17827 Zeroable, Subtarget, DAG))
17828 return Blend;
17829
17830 // Otherwise, fall back to a SHUFPS sequence.
17831 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17832 }
17833
17834 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17835 Zeroable, Subtarget, DAG))
17836 return Blend;
17837
17839 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17840 return DAG.getBitcast(MVT::v16f32, ZExt);
17841
17842 // Try to create an in-lane repeating shuffle mask and then shuffle the
17843 // results into the target lanes.
17845 DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17846 return V;
17847
17848 // If we have a single input shuffle with different shuffle patterns in the
17849 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17850 if (V2.isUndef() &&
17851 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17852 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17853 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17854 }
17855
17856 // If we have AVX512F support, we can use VEXPAND.
17857 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16f32, V1, V2, Mask,
17858 Zeroable, Subtarget, DAG))
17859 return V;
17860
17861 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPS which
17862 // requires an extra register for the index vector; VALIGND uses an immediate.
17863 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16f32, V1, V2, Mask,
17864 Zeroable, Subtarget, DAG))
17865 return Rotate;
17866
17867 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17868}
17869
17870/// Handle lowering of 8-lane 64-bit integer shuffles.
17872 const APInt &Zeroable, SDValue V1, SDValue V2,
17873 const X86Subtarget &Subtarget,
17874 SelectionDAG &DAG) {
17875 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17876 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17877 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17878
17879 // Try to use shift instructions if fast.
17880 if (Subtarget.preferLowerShuffleAsShift())
17881 if (SDValue Shift =
17882 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17883 Subtarget, DAG, /*BitwiseOnly*/ true))
17884 return Shift;
17885
17886 if (V2.isUndef()) {
17887 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17888 // can use lower latency instructions that will operate on all four
17889 // 128-bit lanes.
17890 SmallVector<int, 2> Repeated128Mask;
17891 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17892 SmallVector<int, 4> PSHUFDMask;
17893 narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17894 return DAG.getBitcast(
17895 MVT::v8i64,
17896 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17897 DAG.getBitcast(MVT::v16i32, V1),
17898 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17899 }
17900
17901 SmallVector<int, 4> Repeated256Mask;
17902 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17903 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17904 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17905 }
17906
17907 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17908 V2, Subtarget, DAG))
17909 return Shuf128;
17910
17911 // Try to use shift instructions.
17912 if (SDValue Shift =
17913 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
17914 DAG, /*BitwiseOnly*/ false))
17915 return Shift;
17916
17917 // Try to use VALIGN.
17918 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17919 Zeroable, Subtarget, DAG))
17920 return Rotate;
17921
17922 // Try to use PALIGNR.
17923 if (Subtarget.hasBWI())
17924 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17925 Subtarget, DAG))
17926 return Rotate;
17927
17928 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, V1, V2, Mask, DAG))
17929 return Unpck;
17930
17931 // If we have AVX512F support, we can use VEXPAND.
17932 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17933 Subtarget, DAG))
17934 return V;
17935
17936 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17937 Zeroable, Subtarget, DAG))
17938 return Blend;
17939
17940 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17941}
17942
17943/// Handle lowering of 16-lane 32-bit integer shuffles.
17945 const APInt &Zeroable, SDValue V1, SDValue V2,
17946 const X86Subtarget &Subtarget,
17947 SelectionDAG &DAG) {
17948 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17949 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17950 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17951
17952 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
17953
17954 // Whenever we can lower this as a zext, that instruction is strictly faster
17955 // than any alternative. It also allows us to fold memory operands into the
17956 // shuffle in many cases.
17958 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17959 return ZExt;
17960
17961 // Try to use shift instructions if fast.
17962 if (Subtarget.preferLowerShuffleAsShift()) {
17963 if (SDValue Shift =
17964 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17965 Subtarget, DAG, /*BitwiseOnly*/ true))
17966 return Shift;
17967 if (NumV2Elements == 0)
17968 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
17969 Subtarget, DAG))
17970 return Rotate;
17971 }
17972
17973 // If the shuffle mask is repeated in each 128-bit lane we can use more
17974 // efficient instructions that mirror the shuffles across the four 128-bit
17975 // lanes.
17976 SmallVector<int, 4> RepeatedMask;
17977 bool Is128BitLaneRepeatedShuffle =
17978 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17979 if (Is128BitLaneRepeatedShuffle) {
17980 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17981 if (V2.isUndef())
17982 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17983 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17984
17985 // Use dedicated unpack instructions for masks that match their pattern.
17986 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, V1, V2, Mask, DAG))
17987 return V;
17988 }
17989
17990 // Try to use shift instructions.
17991 if (SDValue Shift =
17992 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17993 Subtarget, DAG, /*BitwiseOnly*/ false))
17994 return Shift;
17995
17996 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
17997 if (SDValue Rotate =
17998 lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
17999 return Rotate;
18000
18001 // Try to use VALIGN.
18002 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
18003 Zeroable, Subtarget, DAG))
18004 return Rotate;
18005
18006 // Try to use byte rotation instructions.
18007 if (Subtarget.hasBWI())
18008 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
18009 Subtarget, DAG))
18010 return Rotate;
18011
18012 // Assume that a single SHUFPS is faster than using a permv shuffle.
18013 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18014 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18015 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
18016 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
18017 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
18018 CastV1, CastV2, DAG);
18019 return DAG.getBitcast(MVT::v16i32, ShufPS);
18020 }
18021
18022 // Try to create an in-lane repeating shuffle mask and then shuffle the
18023 // results into the target lanes.
18025 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
18026 return V;
18027
18028 // If we have AVX512F support, we can use VEXPAND.
18029 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16i32, V1, V2, Mask,
18030 Zeroable, Subtarget, DAG))
18031 return V;
18032
18033 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
18034 Zeroable, Subtarget, DAG))
18035 return Blend;
18036
18037 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
18038}
18039
18040/// Handle lowering of 32-lane 16-bit integer shuffles.
18042 const APInt &Zeroable, SDValue V1, SDValue V2,
18043 const X86Subtarget &Subtarget,
18044 SelectionDAG &DAG) {
18045 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18046 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18047 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18048 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
18049
18050 // Whenever we can lower this as a zext, that instruction is strictly faster
18051 // than any alternative. It also allows us to fold memory operands into the
18052 // shuffle in many cases.
18054 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18055 return ZExt;
18056
18057 // Use dedicated unpack instructions for masks that match their pattern.
18058 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, V1, V2, Mask, DAG))
18059 return V;
18060
18061 // Use dedicated pack instructions for masks that match their pattern.
18062 if (SDValue V =
18063 lowerShuffleWithPACK(DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18064 return V;
18065
18066 // Try to use shift instructions.
18067 if (SDValue Shift =
18068 lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
18069 Subtarget, DAG, /*BitwiseOnly*/ false))
18070 return Shift;
18071
18072 // Try to use byte rotation instructions.
18073 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
18074 Subtarget, DAG))
18075 return Rotate;
18076
18077 if (V2.isUndef()) {
18078 // Try to use bit rotation instructions.
18079 if (SDValue Rotate =
18080 lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
18081 return Rotate;
18082
18083 SmallVector<int, 8> RepeatedMask;
18084 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
18085 // As this is a single-input shuffle, the repeated mask should be
18086 // a strictly valid v8i16 mask that we can pass through to the v8i16
18087 // lowering to handle even the v32 case.
18088 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
18089 RepeatedMask, Subtarget, DAG);
18090 }
18091 }
18092
18093 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
18094 Zeroable, Subtarget, DAG))
18095 return Blend;
18096
18097 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18098 Zeroable, Subtarget, DAG))
18099 return PSHUFB;
18100
18101 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18102 // shuffle.
18104 DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18105 return Result;
18106
18107 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18108}
18109
18110/// Handle lowering of 64-lane 8-bit integer shuffles.
18112 const APInt &Zeroable, SDValue V1, SDValue V2,
18113 const X86Subtarget &Subtarget,
18114 SelectionDAG &DAG) {
18115 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18116 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18117 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
18118 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
18119
18120 // Whenever we can lower this as a zext, that instruction is strictly faster
18121 // than any alternative. It also allows us to fold memory operands into the
18122 // shuffle in many cases.
18124 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18125 return ZExt;
18126
18127 // Use dedicated unpack instructions for masks that match their pattern.
18128 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, V1, V2, Mask, DAG))
18129 return V;
18130
18131 // Use dedicated pack instructions for masks that match their pattern.
18132 if (SDValue V =
18133 lowerShuffleWithPACK(DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18134 return V;
18135
18136 // Try to use shift instructions.
18137 if (SDValue Shift =
18138 lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
18139 DAG, /*BitwiseOnly*/ false))
18140 return Shift;
18141
18142 // Try to use byte rotation instructions.
18143 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18144 Subtarget, DAG))
18145 return Rotate;
18146
18147 // Try to use bit rotation instructions.
18148 if (V2.isUndef())
18149 if (SDValue Rotate =
18150 lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18151 return Rotate;
18152
18153 // Lower as AND if possible.
18154 if (SDValue Masked =
18155 lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask, Zeroable, DAG))
18156 return Masked;
18157
18158 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18159 Zeroable, Subtarget, DAG))
18160 return PSHUFB;
18161
18162 // Try to create an in-lane repeating shuffle mask and then shuffle the
18163 // results into the target lanes.
18164 // FIXME: Avoid on VBMI targets as the post lane permute often interferes
18165 // with shuffle combining (should be fixed by topological DAG sorting).
18166 if (!Subtarget.hasVBMI())
18168 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18169 return V;
18170
18172 DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
18173 return Result;
18174
18175 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18176 Zeroable, Subtarget, DAG))
18177 return Blend;
18178
18179 if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
18180 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
18181 // PALIGNR will be cheaper than the second PSHUFB+OR.
18182 if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
18183 Mask, Subtarget, DAG))
18184 return V;
18185
18186 // VBMI can use VPERMV/VPERMV3 byte shuffles more efficiently than
18187 // OR(PSHUFB,PSHUFB).
18188 if (Subtarget.hasVBMI())
18189 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget,
18190 DAG);
18191
18192 // If we can't directly blend but can use PSHUFB, that will be better as it
18193 // can both shuffle and set up the inefficient blend.
18194 bool V1InUse, V2InUse;
18195 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
18196 DAG, V1InUse, V2InUse);
18197 }
18198
18199 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18200 // shuffle.
18202 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18203 return Result;
18204
18205 // VBMI can use VPERMV/VPERMV3 byte shuffles.
18206 if (Subtarget.hasVBMI())
18207 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18208
18209 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG,
18210 /*SimpleOnly*/ false);
18211}
18212
18213/// High-level routine to lower various 512-bit x86 vector shuffles.
18214///
18215/// This routine either breaks down the specific type of a 512-bit x86 vector
18216/// shuffle or splits it into two 256-bit shuffles and fuses the results back
18217/// together based on the available instructions.
18219 MVT VT, SDValue V1, SDValue V2,
18220 const APInt &Zeroable,
18221 const X86Subtarget &Subtarget,
18222 SelectionDAG &DAG) {
18223 assert(Subtarget.hasAVX512() &&
18224 "Cannot lower 512-bit vectors w/ basic ISA!");
18225
18226 // If we have a single input to the zero element, insert that into V1 if we
18227 // can do so cheaply.
18228 int NumElts = Mask.size();
18229 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18230
18231 if (NumV2Elements == 1 && Mask[0] >= NumElts)
18233 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18234 return Insertion;
18235
18236 // Handle special cases where the lower or upper half is UNDEF.
18237 if (SDValue V =
18238 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18239 return V;
18240
18241 // Check for being able to broadcast a single element.
18242 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
18243 Subtarget, DAG))
18244 return Broadcast;
18245
18246 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
18247 // Try using bit ops for masking and blending before falling back to
18248 // splitting.
18249 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
18250 return V;
18251 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18252 return V;
18253
18254 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
18255 }
18256
18257 if (VT == MVT::v32f16 || VT == MVT::v32bf16) {
18258 if (!Subtarget.hasBWI())
18259 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
18260 /*SimpleOnly*/ false);
18261
18262 V1 = DAG.getBitcast(MVT::v32i16, V1);
18263 V2 = DAG.getBitcast(MVT::v32i16, V2);
18264 return DAG.getBitcast(VT,
18265 DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
18266 }
18267
18268 // Dispatch to each element type for lowering. If we don't have support for
18269 // specific element type shuffles at 512 bits, immediately split them and
18270 // lower them. Each lowering routine of a given type is allowed to assume that
18271 // the requisite ISA extensions for that element type are available.
18272 switch (VT.SimpleTy) {
18273 case MVT::v8f64:
18274 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18275 case MVT::v16f32:
18276 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18277 case MVT::v8i64:
18278 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18279 case MVT::v16i32:
18280 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18281 case MVT::v32i16:
18282 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18283 case MVT::v64i8:
18284 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18285
18286 default:
18287 llvm_unreachable("Not a valid 512-bit x86 vector type!");
18288 }
18289}
18290
18292 MVT VT, SDValue V1, SDValue V2,
18293 const X86Subtarget &Subtarget,
18294 SelectionDAG &DAG) {
18295 // Shuffle should be unary.
18296 if (!V2.isUndef())
18297 return SDValue();
18298
18299 int ShiftAmt = -1;
18300 int NumElts = Mask.size();
18301 for (int i = 0; i != NumElts; ++i) {
18302 int M = Mask[i];
18303 assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
18304 "Unexpected mask index.");
18305 if (M < 0)
18306 continue;
18307
18308 // The first non-undef element determines our shift amount.
18309 if (ShiftAmt < 0) {
18310 ShiftAmt = M - i;
18311 // Need to be shifting right.
18312 if (ShiftAmt <= 0)
18313 return SDValue();
18314 }
18315 // All non-undef elements must shift by the same amount.
18316 if (ShiftAmt != M - i)
18317 return SDValue();
18318 }
18319 assert(ShiftAmt >= 0 && "All undef?");
18320
18321 // Great we found a shift right.
18322 SDValue Res = widenMaskVector(V1, false, Subtarget, DAG, DL);
18323 Res = DAG.getNode(X86ISD::KSHIFTR, DL, Res.getValueType(), Res,
18324 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18325 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18326 DAG.getVectorIdxConstant(0, DL));
18327}
18328
18329// Determine if this shuffle can be implemented with a KSHIFT instruction.
18330// Returns the shift amount if possible or -1 if not. This is a simplified
18331// version of matchShuffleAsShift.
18332static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18333 int MaskOffset, const APInt &Zeroable) {
18334 int Size = Mask.size();
18335
18336 auto CheckZeros = [&](int Shift, bool Left) {
18337 for (int j = 0; j < Shift; ++j)
18338 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18339 return false;
18340
18341 return true;
18342 };
18343
18344 auto MatchShift = [&](int Shift, bool Left) {
18345 unsigned Pos = Left ? Shift : 0;
18346 unsigned Low = Left ? 0 : Shift;
18347 unsigned Len = Size - Shift;
18348 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18349 };
18350
18351 for (int Shift = 1; Shift != Size; ++Shift)
18352 for (bool Left : {true, false})
18353 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18354 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18355 return Shift;
18356 }
18357
18358 return -1;
18359}
18360
18361
18362// Lower vXi1 vector shuffles.
18363// There is no a dedicated instruction on AVX-512 that shuffles the masks.
18364// The only way to shuffle bits is to sign-extend the mask vector to SIMD
18365// vector, shuffle and then truncate it back.
18367 MVT VT, SDValue V1, SDValue V2,
18368 const APInt &Zeroable,
18369 const X86Subtarget &Subtarget,
18370 SelectionDAG &DAG) {
18371 assert(Subtarget.hasAVX512() &&
18372 "Cannot lower 512-bit vectors w/o basic ISA!");
18373
18374 int NumElts = Mask.size();
18375 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18376
18377 // Try to recognize shuffles that are just padding a subvector with zeros.
18378 int SubvecElts = 0;
18379 int Src = -1;
18380 for (int i = 0; i != NumElts; ++i) {
18381 if (Mask[i] >= 0) {
18382 // Grab the source from the first valid mask. All subsequent elements need
18383 // to use this same source.
18384 if (Src < 0)
18385 Src = Mask[i] / NumElts;
18386 if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18387 break;
18388 }
18389
18390 ++SubvecElts;
18391 }
18392 assert(SubvecElts != NumElts && "Identity shuffle?");
18393
18394 // Clip to a power 2.
18395 SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
18396
18397 // Make sure the number of zeroable bits in the top at least covers the bits
18398 // not covered by the subvector.
18399 if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
18400 assert(Src >= 0 && "Expected a source!");
18401 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18402 SDValue Extract =
18403 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, Src == 0 ? V1 : V2,
18404 DAG.getVectorIdxConstant(0, DL));
18405 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18406 DAG.getConstant(0, DL, VT), Extract,
18407 DAG.getVectorIdxConstant(0, DL));
18408 }
18409
18410 // Try a simple shift right with undef elements. Later we'll try with zeros.
18411 if (SDValue Shift =
18412 lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget, DAG))
18413 return Shift;
18414
18415 // Try to match KSHIFTs.
18416 unsigned Offset = 0;
18417 for (SDValue V : {V1, V2}) {
18418 unsigned Opcode;
18419 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18420 if (ShiftAmt >= 0) {
18421 SDValue Res = widenMaskVector(V, false, Subtarget, DAG, DL);
18422 MVT WideVT = Res.getSimpleValueType();
18423 // Widened right shifts need two shifts to ensure we shift in zeroes.
18424 if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18425 int WideElts = WideVT.getVectorNumElements();
18426 // Shift left to put the original vector in the MSBs of the new size.
18427 Res =
18428 DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18429 DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18430 // Increase the shift amount to account for the left shift.
18431 ShiftAmt += WideElts - NumElts;
18432 }
18433
18434 Res = DAG.getNode(Opcode, DL, WideVT, Res,
18435 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18436 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18437 DAG.getVectorIdxConstant(0, DL));
18438 }
18439 Offset += NumElts; // Increment for next iteration.
18440 }
18441
18442 // If we're performing an unary shuffle on a SETCC result, try to shuffle the
18443 // ops instead.
18444 // TODO: What other unary shuffles would benefit from this?
18445 if (NumV2Elements == 0 && V1.getOpcode() == ISD::SETCC && V1->hasOneUse()) {
18446 SDValue Op0 = V1.getOperand(0);
18447 SDValue Op1 = V1.getOperand(1);
18448 ISD::CondCode CC = V1.getOperandCondCode(2);
18449 EVT OpVT = Op0.getValueType();
18450 if (OpVT.getScalarSizeInBits() >= 32 || isBroadcastShuffleMask(Mask))
18451 return DAG.getSetCC(
18452 DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
18453 DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
18454 }
18455
18456 // If this is a sequential shuffle with zero'd elements - then lower to AND.
18457 bool IsBlendWithZero = all_of(enumerate(Mask), [&Zeroable](auto M) {
18458 return Zeroable[M.index()] || (M.value() == (int)M.index());
18459 });
18460 if (IsBlendWithZero) {
18461 const unsigned Width = std::max<unsigned>(NumElts, 8u);
18462 MVT IntVT = MVT::getIntegerVT(Width);
18463
18464 APInt MaskValue = (~Zeroable).zextOrTrunc(Width);
18465 SDValue MaskNode = DAG.getConstant(MaskValue, DL, IntVT);
18466
18467 MVT MaskVecVT = MVT::getVectorVT(MVT::i1, Width);
18468 SDValue MaskVecNode = DAG.getBitcast(MaskVecVT, MaskNode);
18469
18470 SDValue MaskVec = DAG.getExtractSubvector(DL, VT, MaskVecNode, 0);
18471 return DAG.getNode(ISD::AND, DL, VT, V1, MaskVec);
18472 }
18473
18474 MVT ExtVT;
18475 switch (VT.SimpleTy) {
18476 default:
18477 llvm_unreachable("Expected a vector of i1 elements");
18478 case MVT::v2i1:
18479 ExtVT = MVT::v2i64;
18480 break;
18481 case MVT::v4i1:
18482 ExtVT = MVT::v4i32;
18483 break;
18484 case MVT::v8i1:
18485 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18486 // shuffle.
18487 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18488 break;
18489 case MVT::v16i1:
18490 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18491 // 256-bit operation available.
18492 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18493 break;
18494 case MVT::v32i1:
18495 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18496 // 256-bit operation available.
18497 assert(Subtarget.hasBWI() && "Expected AVX512BW support");
18498 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18499 break;
18500 case MVT::v64i1:
18501 // Fall back to scalarization. FIXME: We can do better if the shuffle
18502 // can be partitioned cleanly.
18503 if (!Subtarget.useBWIRegs())
18504 return SDValue();
18505 ExtVT = MVT::v64i8;
18506 break;
18507 }
18508
18509 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18510 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18511
18512 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18513 // i1 was sign extended we can use X86ISD::CVT2MASK.
18514 int NumElems = VT.getVectorNumElements();
18515 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18516 (Subtarget.hasDQI() && (NumElems < 32)))
18517 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18518 Shuffle, ISD::SETGT);
18519
18520 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18521}
18522
18523/// Helper function that returns true if the shuffle mask should be
18524/// commuted to improve canonicalization.
18526 int NumElements = Mask.size();
18527
18528 int NumV1Elements = 0, NumV2Elements = 0;
18529 for (int M : Mask)
18530 if (M < 0)
18531 continue;
18532 else if (M < NumElements)
18533 ++NumV1Elements;
18534 else
18535 ++NumV2Elements;
18536
18537 // Commute the shuffle as needed such that more elements come from V1 than
18538 // V2. This allows us to match the shuffle pattern strictly on how many
18539 // elements come from V1 without handling the symmetric cases.
18540 if (NumV2Elements > NumV1Elements)
18541 return true;
18542
18543 assert(NumV1Elements > 0 && "No V1 indices");
18544
18545 if (NumV2Elements == 0)
18546 return false;
18547
18548 // When the number of V1 and V2 elements are the same, try to minimize the
18549 // number of uses of V2 in the low half of the vector. When that is tied,
18550 // ensure that the sum of indices for V1 is equal to or lower than the sum
18551 // indices for V2. When those are equal, try to ensure that the number of odd
18552 // indices for V1 is lower than the number of odd indices for V2.
18553 if (NumV1Elements == NumV2Elements) {
18554 int LowV1Elements = 0, LowV2Elements = 0;
18555 for (int M : Mask.slice(0, NumElements / 2))
18556 if (M >= NumElements)
18557 ++LowV2Elements;
18558 else if (M >= 0)
18559 ++LowV1Elements;
18560 if (LowV2Elements > LowV1Elements)
18561 return true;
18562 if (LowV2Elements == LowV1Elements) {
18563 int SumV1Indices = 0, SumV2Indices = 0;
18564 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18565 if (Mask[i] >= NumElements)
18566 SumV2Indices += i;
18567 else if (Mask[i] >= 0)
18568 SumV1Indices += i;
18569 if (SumV2Indices < SumV1Indices)
18570 return true;
18571 if (SumV2Indices == SumV1Indices) {
18572 int NumV1OddIndices = 0, NumV2OddIndices = 0;
18573 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18574 if (Mask[i] >= NumElements)
18575 NumV2OddIndices += i % 2;
18576 else if (Mask[i] >= 0)
18577 NumV1OddIndices += i % 2;
18578 if (NumV2OddIndices < NumV1OddIndices)
18579 return true;
18580 }
18581 }
18582 }
18583
18584 return false;
18585}
18586
18588 const X86Subtarget &Subtarget) {
18589 if (!Subtarget.hasAVX512())
18590 return false;
18591
18592 if (!V.getValueType().isSimple())
18593 return false;
18594
18595 MVT VT = V.getSimpleValueType().getScalarType();
18596 if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
18597 return false;
18598
18599 // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
18600 // are preferable to blendw/blendvb/masked-mov.
18601 if ((VT == MVT::i16 || VT == MVT::i8) &&
18602 V.getSimpleValueType().getSizeInBits() < 512)
18603 return false;
18604
18605 auto HasMaskOperation = [&](SDValue V) {
18606 // TODO: Currently we only check limited opcode. We probably extend
18607 // it to all binary operation by checking TLI.isBinOp().
18608 switch (V->getOpcode()) {
18609 default:
18610 return false;
18611 case ISD::ADD:
18612 case ISD::SUB:
18613 case ISD::AND:
18614 case ISD::XOR:
18615 case ISD::OR:
18616 case ISD::SMAX:
18617 case ISD::SMIN:
18618 case ISD::UMAX:
18619 case ISD::UMIN:
18620 case ISD::ABS:
18621 case ISD::SHL:
18622 case ISD::SRL:
18623 case ISD::SRA:
18624 case ISD::MUL:
18625 case ISD::PSEUDO_FMIN:
18626 case ISD::PSEUDO_FMAX:
18627 break;
18628 }
18629 if (!V->hasOneUse())
18630 return false;
18631
18632 return true;
18633 };
18634
18635 if (HasMaskOperation(V))
18636 return true;
18637
18638 return false;
18639}
18640
18641// Forward declaration.
18644 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
18645 const X86Subtarget &Subtarget);
18646
18647 /// Top-level lowering for x86 vector shuffles.
18648///
18649/// This handles decomposition, canonicalization, and lowering of all x86
18650/// vector shuffles. Most of the specific lowering strategies are encapsulated
18651/// above in helper routines. The canonicalization attempts to widen shuffles
18652/// to involve fewer lanes of wider elements, consolidate symmetric patterns
18653/// s.t. only one of the two inputs needs to be tested, etc.
18655 SelectionDAG &DAG) {
18657 ArrayRef<int> OrigMask = SVOp->getMask();
18658 SDValue V1 = Op.getOperand(0);
18659 SDValue V2 = Op.getOperand(1);
18660 MVT VT = Op.getSimpleValueType();
18661 int NumElements = VT.getVectorNumElements();
18662 SDLoc DL(Op);
18663 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18664
18665 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
18666 "Can't lower MMX shuffles");
18667
18668 bool V1IsUndef = V1.isUndef();
18669 bool V2IsUndef = V2.isUndef();
18670 if (V1IsUndef && V2IsUndef)
18671 return DAG.getUNDEF(VT);
18672
18673 // When we create a shuffle node we put the UNDEF node to second operand,
18674 // but in some cases the first operand may be transformed to UNDEF.
18675 // In this case we should just commute the node.
18676 if (V1IsUndef)
18677 return DAG.getCommutedVectorShuffle(*SVOp);
18678
18679 // Check for non-undef masks pointing at an undef vector and make the masks
18680 // undef as well. This makes it easier to match the shuffle based solely on
18681 // the mask.
18682 if (V2IsUndef &&
18683 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18684 SmallVector<int, 8> NewMask(OrigMask);
18685 for (int &M : NewMask)
18686 if (M >= NumElements)
18687 M = -1;
18688 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18689 }
18690
18691 // Check for illegal shuffle mask element index values.
18692 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18693 (void)MaskUpperLimit;
18694 assert(llvm::all_of(OrigMask,
18695 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
18696 "Out of bounds shuffle index");
18697
18698 // We actually see shuffles that are entirely re-arrangements of a set of
18699 // zero inputs. This mostly happens while decomposing complex shuffles into
18700 // simple ones. Directly lower these as a buildvector of zeros.
18701 APInt KnownUndef, KnownZero;
18702 computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
18703
18704 APInt Zeroable = KnownUndef | KnownZero;
18705 if (Zeroable.isAllOnes())
18706 return getZeroVector(VT, Subtarget, DAG, DL);
18707
18708 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
18709
18710 // Try to collapse shuffles into using a vector type with fewer elements but
18711 // wider element types. We cap this to not form integers or floating point
18712 // elements wider than 64 bits. It does not seem beneficial to form i128
18713 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
18714 SmallVector<int, 16> WidenedMask;
18715 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
18718 canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
18719 // Shuffle mask widening should not interfere with a broadcast opportunity
18720 // by obfuscating the operands with bitcasts.
18721 // TODO: Avoid lowering directly from this top-level function: make this
18722 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
18723 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
18724 Subtarget, DAG))
18725 return Broadcast;
18726
18727 MVT NewEltVT = VT.isFloatingPoint()
18730 int NewNumElts = NumElements / 2;
18731 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
18732 // Make sure that the new vector type is legal. For example, v2f64 isn't
18733 // legal on SSE1.
18734 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
18735 if (V2IsZero) {
18736 // Modify the new Mask to take all zeros from the all-zero vector.
18737 // Choose indices that are blend-friendly.
18738 bool UsedZeroVector = false;
18739 assert(is_contained(WidenedMask, SM_SentinelZero) &&
18740 "V2's non-undef elements are used?!");
18741 for (int i = 0; i != NewNumElts; ++i)
18742 if (WidenedMask[i] == SM_SentinelZero) {
18743 WidenedMask[i] = i + NewNumElts;
18744 UsedZeroVector = true;
18745 }
18746 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
18747 // some elements to be undef.
18748 if (UsedZeroVector)
18749 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
18750 }
18751 V1 = DAG.getBitcast(NewVT, V1);
18752 V2 = DAG.getBitcast(NewVT, V2);
18753 return DAG.getBitcast(
18754 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
18755 }
18756 }
18757
18758 SmallVector<SDValue> Ops = {V1, V2};
18759 SmallVector<int> Mask(OrigMask);
18760
18761 // Canonicalize the shuffle with any horizontal ops inputs.
18762 // Don't attempt this if the shuffle can still be widened as we may lose
18763 // whole lane shuffle patterns.
18764 // NOTE: This may update Ops and Mask.
18765 if (!canWidenShuffleElements(Mask)) {
18767 Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
18768 return DAG.getBitcast(VT, HOp);
18769
18770 V1 = DAG.getBitcast(VT, Ops[0]);
18771 V2 = DAG.getBitcast(VT, Ops[1]);
18772 assert(NumElements == (int)Mask.size() &&
18773 "canonicalizeShuffleMaskWithHorizOp "
18774 "shouldn't alter the shuffle mask size");
18775 }
18776
18777 // Canonicalize zeros/ones/fp splat constants to ensure no undefs.
18778 // These will be materialized uniformly anyway, so make splat matching easier.
18779 // TODO: Allow all int constants?
18780 auto CanonicalizeConstant = [VT, &DL, &DAG](SDValue V) {
18781 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
18782 BitVector Undefs;
18783 if (SDValue Splat = BV->getSplatValue(&Undefs)) {
18784 if (Undefs.any() &&
18787 V = DAG.getBitcast(VT, DAG.getSplat(BV->getValueType(0), DL, Splat));
18788 }
18789 }
18790 }
18791 return V;
18792 };
18793 V1 = CanonicalizeConstant(V1);
18794 V2 = CanonicalizeConstant(V2);
18795
18796 // Commute the shuffle if it will improve canonicalization.
18799 std::swap(V1, V2);
18800 }
18801
18802 // For each vector width, delegate to a specialized lowering routine.
18803 if (VT.is128BitVector())
18804 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18805
18806 if (VT.is256BitVector())
18807 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18808
18809 if (VT.is512BitVector())
18810 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18811
18812 if (Is1BitVector)
18813 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18814
18815 llvm_unreachable("Unimplemented!");
18816}
18817
18818// As legal vpcompress instructions depend on various AVX512 extensions, try to
18819// convert illegal vector sizes to legal ones to avoid expansion.
18821 SelectionDAG &DAG) {
18822 assert(Subtarget.hasAVX512() &&
18823 "Need AVX512 for custom VECTOR_COMPRESS lowering.");
18824
18825 SDLoc DL(Op);
18826 SDValue Vec = Op.getOperand(0);
18827 SDValue Mask = Op.getOperand(1);
18828 SDValue Passthru = Op.getOperand(2);
18829
18830 EVT VecVT = Vec.getValueType();
18831 EVT ElementVT = VecVT.getVectorElementType();
18832 unsigned NumElements = VecVT.getVectorNumElements();
18833 unsigned NumVecBits = VecVT.getFixedSizeInBits();
18834 unsigned NumElementBits = ElementVT.getFixedSizeInBits();
18835
18836 // 128- and 256-bit vectors with <= 16 elements can be converted to and
18837 // compressed as 512-bit vectors in AVX512F.
18838 if (NumVecBits != 128 && NumVecBits != 256)
18839 return SDValue();
18840
18841 if (NumElementBits == 32 || NumElementBits == 64) {
18842 unsigned NumLargeElements = 512 / NumElementBits;
18843 MVT LargeVecVT =
18844 MVT::getVectorVT(ElementVT.getSimpleVT(), NumLargeElements);
18845 MVT LargeMaskVT = MVT::getVectorVT(MVT::i1, NumLargeElements);
18846
18847 Vec = widenSubVector(LargeVecVT, Vec, /*ZeroNewElements=*/false, Subtarget,
18848 DAG, DL);
18849 Mask = widenSubVector(LargeMaskVT, Mask, /*ZeroNewElements=*/true,
18850 Subtarget, DAG, DL);
18851 Passthru = Passthru.isUndef() ? DAG.getUNDEF(LargeVecVT)
18852 : widenSubVector(LargeVecVT, Passthru,
18853 /*ZeroNewElements=*/false,
18854 Subtarget, DAG, DL);
18855
18856 SDValue Compressed =
18857 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18858 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VecVT, Compressed,
18859 DAG.getConstant(0, DL, MVT::i64));
18860 }
18861
18862 if (VecVT == MVT::v8i16 || VecVT == MVT::v8i8 || VecVT == MVT::v16i8 ||
18863 VecVT == MVT::v16i16) {
18864 MVT LageElementVT = MVT::getIntegerVT(512 / NumElements);
18865 EVT LargeVecVT = MVT::getVectorVT(LageElementVT, NumElements);
18866
18867 Vec = DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Vec);
18868 Passthru = Passthru.isUndef()
18869 ? DAG.getUNDEF(LargeVecVT)
18870 : DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Passthru);
18871
18872 SDValue Compressed =
18873 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18874 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Compressed);
18875 }
18876
18877 return SDValue();
18878}
18879
18880/// Try to lower a VSELECT instruction to a vector shuffle.
18882 const X86Subtarget &Subtarget,
18883 SelectionDAG &DAG) {
18884 SDValue Cond = Op.getOperand(0);
18885 SDValue LHS = Op.getOperand(1);
18886 SDValue RHS = Op.getOperand(2);
18887 MVT VT = Op.getSimpleValueType();
18888
18889 // Only non-legal VSELECTs reach this lowering, convert those into generic
18890 // shuffles and re-use the shuffle lowering path for blends.
18894 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18895 }
18896
18897 return SDValue();
18898}
18899
18900SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18901 SDValue Cond = Op.getOperand(0);
18902 SDValue LHS = Op.getOperand(1);
18903 SDValue RHS = Op.getOperand(2);
18904
18905 SDLoc dl(Op);
18906 MVT VT = Op.getSimpleValueType();
18907 if (isSoftF16(VT, Subtarget)) {
18908 MVT NVT = VT.changeVectorElementTypeToInteger();
18909 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
18910 DAG.getBitcast(NVT, LHS),
18911 DAG.getBitcast(NVT, RHS)));
18912 }
18913
18914 // A vselect where all conditions and data are constants can be optimized into
18915 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18919 return SDValue();
18920
18921 // Try to lower this to a blend-style vector shuffle. This can handle all
18922 // constant condition cases.
18923 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18924 return BlendOp;
18925
18926 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18927 // with patterns on the mask registers on AVX-512.
18928 MVT CondVT = Cond.getSimpleValueType();
18929 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18930 if (CondEltSize == 1)
18931 return Op;
18932
18933 // Variable blends are only legal from SSE4.1 onward.
18934 if (!Subtarget.hasSSE41())
18935 return SDValue();
18936
18937 unsigned EltSize = VT.getScalarSizeInBits();
18938 unsigned NumElts = VT.getVectorNumElements();
18939
18940 // Expand v32i16/v64i8 without BWI.
18941 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18942 return SDValue();
18943
18944 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18945 // into an i1 condition so that we can use the mask-based 512-bit blend
18946 // instructions.
18947 if (VT.getSizeInBits() == 512) {
18948 // Build a mask by testing the condition against zero.
18949 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18950 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18951 DAG.getConstant(0, dl, CondVT),
18952 ISD::SETNE);
18953 // Now return a new VSELECT using the mask.
18954 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18955 }
18956
18957 // SEXT/TRUNC cases where the mask doesn't match the destination size.
18958 if (CondEltSize != EltSize) {
18959 // If we don't have a sign splat, rely on the expansion.
18960 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18961 return SDValue();
18962
18963 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18964 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18965 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18966 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18967 }
18968
18969 // v16i16/v32i8 selects without AVX2, if the condition and another operand
18970 // are free to split, then better to split before expanding the
18971 // select. Don't bother with XOP as it has the fast VPCMOV instruction.
18972 // TODO: This is very similar to narrowVectorSelect.
18973 // TODO: Add Load splitting to isFreeToSplitVector ?
18974 if (EltSize < 32 && VT.is256BitVector() && !Subtarget.hasAVX2() &&
18975 !Subtarget.hasXOP()) {
18976 bool FreeCond = isFreeToSplitVector(Cond, DAG);
18977 bool FreeLHS = isFreeToSplitVector(LHS, DAG) ||
18978 (ISD::isNormalLoad(LHS.getNode()) && LHS.hasOneUse());
18979 bool FreeRHS = isFreeToSplitVector(RHS, DAG) ||
18980 (ISD::isNormalLoad(RHS.getNode()) && RHS.hasOneUse());
18981 if (FreeCond && (FreeLHS || FreeRHS))
18982 return splitVectorOp(Op, DAG, dl);
18983 }
18984
18985 // Only some types will be legal on some subtargets. If we can emit a legal
18986 // VSELECT-matching blend, return Op, and but if we need to expand, return
18987 // a null value.
18988 switch (VT.SimpleTy) {
18989 default:
18990 // Most of the vector types have blends past SSE4.1.
18991 return Op;
18992
18993 case MVT::v32i8:
18994 // The byte blends for AVX vectors were introduced only in AVX2.
18995 if (Subtarget.hasAVX2())
18996 return Op;
18997
18998 return SDValue();
18999
19000 case MVT::v8i16:
19001 case MVT::v16i16:
19002 case MVT::v8f16:
19003 case MVT::v16f16: {
19004 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
19005 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
19006 Cond = DAG.getBitcast(CastVT, Cond);
19007 LHS = DAG.getBitcast(CastVT, LHS);
19008 RHS = DAG.getBitcast(CastVT, RHS);
19009 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
19010 return DAG.getBitcast(VT, Select);
19011 }
19012 }
19013}
19014
19016 MVT VT = Op.getSimpleValueType();
19017 SDValue Vec = Op.getOperand(0);
19018 SDValue Idx = Op.getOperand(1);
19019 assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
19020 SDLoc dl(Op);
19021
19023 return SDValue();
19024
19025 if (VT.getSizeInBits() == 8) {
19026 // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
19027 // we're going to zero extend the register or fold the store.
19030 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
19031 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19032 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19033
19034 unsigned IdxVal = Idx->getAsZExtVal();
19035 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
19036 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19037 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19038 }
19039
19040 if (VT == MVT::f32) {
19041 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
19042 // the result back to FR32 register. It's only worth matching if the
19043 // result has a single use which is a store or a bitcast to i32. And in
19044 // the case of a store, it's not worth it if the index is a constant 0,
19045 // because a MOVSSmr can be used instead, which is smaller and faster.
19046 if (!Op.hasOneUse())
19047 return SDValue();
19048 SDNode *User = *Op.getNode()->user_begin();
19049 if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
19050 (User->getOpcode() != ISD::BITCAST ||
19051 User->getValueType(0) != MVT::i32))
19052 return SDValue();
19053 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19054 DAG.getBitcast(MVT::v4i32, Vec), Idx);
19055 return DAG.getBitcast(MVT::f32, Extract);
19056 }
19057
19058 if (VT == MVT::i32 || VT == MVT::i64)
19059 return Op;
19060
19061 return SDValue();
19062}
19063
19064/// Extract one bit from mask vector, like v16i1 or v8i1.
19065/// AVX-512 feature.
19067 const X86Subtarget &Subtarget) {
19068 SDValue Vec = Op.getOperand(0);
19069 SDLoc dl(Vec);
19070 MVT VecVT = Vec.getSimpleValueType();
19071 SDValue Idx = Op.getOperand(1);
19072 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19073 MVT EltVT = Op.getSimpleValueType();
19074
19075 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
19076 "Unexpected vector type in ExtractBitFromMaskVector");
19077
19078 // variable index can't be handled in mask registers,
19079 // extend vector to VR512/128
19080 if (!IdxC) {
19081 unsigned NumElts = VecVT.getVectorNumElements();
19082 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
19083 // than extending to 128/256bit.
19084 if (NumElts == 1) {
19085 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19087 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, DAG.getBitcast(IntVT, Vec));
19088 }
19089 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19090 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19091 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
19092 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
19093 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
19094 }
19095
19096 unsigned IdxVal = IdxC->getZExtValue();
19097 if (IdxVal == 0) // the operation is legal
19098 return Op;
19099
19100 // Extend to natively supported kshift.
19101 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19102
19103 // Use kshiftr instruction to move to the lower element.
19104 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19105 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19106
19107 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19108 DAG.getVectorIdxConstant(0, dl));
19109}
19110
19111// Helper to find all the extracted elements from a vector.
19113 MVT VT = N->getSimpleValueType(0);
19114 unsigned NumElts = VT.getVectorNumElements();
19115 APInt DemandedElts = APInt::getZero(NumElts);
19116 for (SDNode *User : N->users()) {
19117 switch (User->getOpcode()) {
19118 case X86ISD::PEXTRB:
19119 case X86ISD::PEXTRW:
19122 DemandedElts.setAllBits();
19123 return DemandedElts;
19124 }
19125 DemandedElts.setBit(User->getConstantOperandVal(1));
19126 break;
19127 case ISD::BITCAST: {
19128 if (!User->getValueType(0).isSimple() ||
19129 !User->getValueType(0).isVector()) {
19130 DemandedElts.setAllBits();
19131 return DemandedElts;
19132 }
19133 APInt DemandedSrcElts = getExtractedDemandedElts(User);
19134 DemandedElts |= APIntOps::ScaleBitMask(DemandedSrcElts, NumElts);
19135 break;
19136 }
19137 default:
19138 DemandedElts.setAllBits();
19139 return DemandedElts;
19140 }
19141 }
19142 return DemandedElts;
19143}
19144
19145SDValue
19146X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
19147 SelectionDAG &DAG) const {
19148 SDLoc dl(Op);
19149 SDValue Vec = Op.getOperand(0);
19150 MVT VecVT = Vec.getSimpleValueType();
19151 SDValue Idx = Op.getOperand(1);
19152 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19153
19154 if (VecVT.getVectorElementType() == MVT::i1)
19155 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
19156
19157 if (!IdxC) {
19158 // Its more profitable to go through memory (1 cycles throughput)
19159 // than using VMOVD + VPERMV/PSHUFB sequence (2/3 cycles throughput)
19160 // IACA tool was used to get performance estimation
19161 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
19162 //
19163 // example : extractelement <16 x i8> %a, i32 %i
19164 //
19165 // Block Throughput: 3.00 Cycles
19166 // Throughput Bottleneck: Port5
19167 //
19168 // | Num Of | Ports pressure in cycles | |
19169 // | Uops | 0 - DV | 5 | 6 | 7 | |
19170 // ---------------------------------------------
19171 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
19172 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
19173 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
19174 // Total Num Of Uops: 4
19175 //
19176 //
19177 // Block Throughput: 1.00 Cycles
19178 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
19179 //
19180 // | | Ports pressure in cycles | |
19181 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
19182 // ---------------------------------------------------------
19183 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
19184 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
19185 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
19186 // Total Num Of Uops: 4
19187
19188 return SDValue();
19189 }
19190
19191 unsigned IdxVal = IdxC->getZExtValue();
19192
19193 // If this is a 256-bit vector result, first extract the 128-bit vector and
19194 // then extract the element from the 128-bit vector.
19195 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
19196 // Get the 128-bit vector.
19197 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
19198 MVT EltVT = VecVT.getVectorElementType();
19199
19200 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
19201 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
19202
19203 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
19204 // this can be done with a mask.
19205 IdxVal &= ElemsPerChunk - 1;
19206 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19207 DAG.getVectorIdxConstant(IdxVal, dl));
19208 }
19209
19210 assert(VecVT.is128BitVector() && "Unexpected vector length");
19211
19212 MVT VT = Op.getSimpleValueType();
19213
19214 if (VT == MVT::i16) {
19215 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
19216 // we're going to zero extend the register or fold the store (SSE41 only).
19217 if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
19218 !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
19219 if (Subtarget.hasFP16())
19220 return Op;
19221
19222 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
19223 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19224 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19225 }
19226
19227 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
19228 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19229 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19230 }
19231
19232 if (Subtarget.hasSSE41())
19233 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
19234 return Res;
19235
19236 // Only extract a single element from a v16i8 source - determine the common
19237 // DWORD/WORD that all extractions share, and extract the sub-byte.
19238 // TODO: Add QWORD MOVQ extraction?
19239 if (VT == MVT::i8) {
19240 APInt DemandedElts = getExtractedDemandedElts(Vec.getNode());
19241 assert(DemandedElts.getBitWidth() == 16 && "Vector width mismatch");
19242
19243 // Extract either the lowest i32 or any i16, and extract the sub-byte.
19244 int DWordIdx = IdxVal / 4;
19245 if (DWordIdx == 0 && DemandedElts == (DemandedElts & 15)) {
19246 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19247 DAG.getBitcast(MVT::v4i32, Vec),
19248 DAG.getVectorIdxConstant(DWordIdx, dl));
19249 int ShiftVal = (IdxVal % 4) * 8;
19250 if (ShiftVal != 0)
19251 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
19252 DAG.getConstant(ShiftVal, dl, MVT::i8));
19253 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19254 }
19255
19256 int WordIdx = IdxVal / 2;
19257 if (DemandedElts == (DemandedElts & (3 << (WordIdx * 2)))) {
19258 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
19259 DAG.getBitcast(MVT::v8i16, Vec),
19260 DAG.getVectorIdxConstant(WordIdx, dl));
19261 int ShiftVal = (IdxVal % 2) * 8;
19262 if (ShiftVal != 0)
19263 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
19264 DAG.getConstant(ShiftVal, dl, MVT::i8));
19265 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19266 }
19267 }
19268
19269 if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
19270 if (IdxVal == 0)
19271 return Op;
19272
19273 // Shuffle the element to the lowest element, then movss or movsh.
19274 SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
19275 Mask[0] = static_cast<int>(IdxVal);
19276 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19277 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19278 DAG.getVectorIdxConstant(0, dl));
19279 }
19280
19281 if (VT.getSizeInBits() == 64) {
19282 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
19283 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
19284 // to match extract_elt for f64.
19285 if (IdxVal == 0)
19286 return Op;
19287
19288 // UNPCKHPD the element to the lowest double word, then movsd.
19289 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
19290 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
19291 int Mask[2] = { 1, -1 };
19292 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19293 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19294 DAG.getVectorIdxConstant(0, dl));
19295 }
19296
19297 return SDValue();
19298}
19299
19300/// Insert one bit to mask vector, like v16i1 or v8i1.
19301/// AVX-512 feature.
19303 const X86Subtarget &Subtarget) {
19304 SDLoc dl(Op);
19305 SDValue Vec = Op.getOperand(0);
19306 SDValue Elt = Op.getOperand(1);
19307 SDValue Idx = Op.getOperand(2);
19308 MVT VecVT = Vec.getSimpleValueType();
19309
19310 if (!isa<ConstantSDNode>(Idx)) {
19311 // Non constant index. Extend source and destination,
19312 // insert element and then truncate the result.
19313 unsigned NumElts = VecVT.getVectorNumElements();
19314 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19315 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19316 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
19317 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
19318 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
19319 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
19320 }
19321
19322 // Copy into a k-register, extract to v1i1 and insert_subvector.
19323 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
19324 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
19325}
19326
19327SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
19328 SelectionDAG &DAG) const {
19329 MVT VT = Op.getSimpleValueType();
19330 MVT EltVT = VT.getVectorElementType();
19331 unsigned NumElts = VT.getVectorNumElements();
19332 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
19333
19334 if (EltVT == MVT::i1)
19335 return InsertBitToMaskVector(Op, DAG, Subtarget);
19336
19337 SDLoc dl(Op);
19338 SDValue N0 = Op.getOperand(0);
19339 SDValue N1 = Op.getOperand(1);
19340 SDValue N2 = Op.getOperand(2);
19341 auto *N2C = dyn_cast<ConstantSDNode>(N2);
19342
19343 if (!N2C) {
19344 // Variable insertion indices, usually we're better off spilling to stack,
19345 // but AVX512 can use a variable compare+select by comparing against all
19346 // possible vector indices, and FP insertion has less gpr->simd traffic.
19347 if (!(Subtarget.hasBWI() ||
19348 (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
19349 (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
19350 return SDValue();
19351
19352 MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
19353 MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
19354 if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
19355 return SDValue();
19356
19357 SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
19358 SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
19359 SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
19360
19361 SmallVector<SDValue, 16> RawIndices;
19362 for (unsigned I = 0; I != NumElts; ++I)
19363 RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
19364 SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
19365
19366 // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
19367 return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
19369 }
19370
19371 if (N2C->getAPIntValue().uge(NumElts))
19372 return SDValue();
19373 uint64_t IdxVal = N2C->getZExtValue();
19374
19375 bool IsZeroElt = X86::isZeroNode(N1);
19376 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
19377
19378 if (IsZeroElt || IsAllOnesElt) {
19379 // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
19380 // We don't deal with i8 0 since it appears to be handled elsewhere.
19381 if (IsAllOnesElt &&
19382 ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
19383 ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
19384 SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
19385 SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
19386 SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
19387 CstVectorElts[IdxVal] = OnesCst;
19388 SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
19389 return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
19390 }
19391 // See if we can do this more efficiently with a blend shuffle with a
19392 // rematerializable vector.
19393 if (Subtarget.hasSSE41() &&
19394 (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
19395 SmallVector<int, 8> BlendMask;
19396 for (unsigned i = 0; i != NumElts; ++i)
19397 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19398 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
19399 : getOnesVector(VT, DAG, dl);
19400 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
19401 }
19402 }
19403
19404 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
19405 // into that, and then insert the subvector back into the result.
19406 if (VT.is256BitVector() || VT.is512BitVector()) {
19407 // With a 256-bit vector, we can insert into the zero element efficiently
19408 // using a blend if we have AVX or AVX2 and the right data type.
19409 if (VT.is256BitVector() && IdxVal == 0) {
19410 // TODO: It is worthwhile to cast integer to floating point and back
19411 // and incur a domain crossing penalty if that's what we'll end up
19412 // doing anyway after extracting to a 128-bit vector.
19413 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19414 (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
19415 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19416 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19417 DAG.getTargetConstant(1, dl, MVT::i8));
19418 }
19419 }
19420
19421 unsigned NumEltsIn128 = 128 / EltSizeInBits;
19422 assert(isPowerOf2_32(NumEltsIn128) &&
19423 "Vectors will always have power-of-two number of elements.");
19424
19425 // If we are not inserting into the low 128-bit vector chunk,
19426 // then prefer the broadcast+blend sequence.
19427 // FIXME: relax the profitability check iff all N1 uses are insertions.
19428 if (IdxVal >= NumEltsIn128 &&
19429 ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
19430 (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
19431 X86::mayFoldLoad(N1, Subtarget)))) {
19432 SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
19433 SmallVector<int, 8> BlendMask;
19434 for (unsigned i = 0; i != NumElts; ++i)
19435 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19436 return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
19437 }
19438
19439 // Get the desired 128-bit vector chunk.
19440 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
19441
19442 // Insert the element into the desired chunk.
19443 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
19444 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
19445
19446 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
19447 DAG.getVectorIdxConstant(IdxIn128, dl));
19448
19449 // Insert the changed part back into the bigger vector
19450 return insert128BitVector(N0, V, IdxVal, DAG, dl);
19451 }
19452 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
19453
19454 // This will be just movw/movd/movq/movsh/movss/movsd.
19455 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
19456 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
19457 EltVT == MVT::f16 || EltVT == MVT::i64) {
19458 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19459 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19460 }
19461
19462 // We can't directly insert an i8 or i16 into a vector, so zero extend
19463 // it to i32 first.
19464 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
19465 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
19466 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
19467 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
19468 N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19469 return DAG.getBitcast(VT, N1);
19470 }
19471 }
19472
19473 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
19474 // argument. SSE41 required for pinsrb.
19475 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
19476 unsigned Opc;
19477 if (VT == MVT::v8i16) {
19478 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
19479 Opc = X86ISD::PINSRW;
19480 } else {
19481 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
19482 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
19483 Opc = X86ISD::PINSRB;
19484 }
19485
19486 assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
19487 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
19488 N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
19489 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
19490 }
19491
19492 if (Subtarget.hasSSE41()) {
19493 if (EltVT == MVT::f32) {
19494 // Bits [7:6] of the constant are the source select. This will always be
19495 // zero here. The DAG Combiner may combine an extract_elt index into
19496 // these bits. For example (insert (extract, 3), 2) could be matched by
19497 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
19498 // Bits [5:4] of the constant are the destination select. This is the
19499 // value of the incoming immediate.
19500 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
19501 // combine either bitwise AND or insert of float 0.0 to set these bits.
19502
19503 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
19504 if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
19505 // If this is an insertion of 32-bits into the low 32-bits of
19506 // a vector, we prefer to generate a blend with immediate rather
19507 // than an insertps. Blends are simpler operations in hardware and so
19508 // will always have equal or better performance than insertps.
19509 // But if optimizing for size and there's a load folding opportunity,
19510 // generate insertps because blendps does not have a 32-bit memory
19511 // operand form.
19512 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19513 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
19514 DAG.getTargetConstant(1, dl, MVT::i8));
19515 }
19516 // Create this as a scalar to vector..
19517 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19518 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
19519 DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
19520 }
19521
19522 // PINSR* works with constant index.
19523 if (EltVT == MVT::i32 || EltVT == MVT::i64)
19524 return Op;
19525 }
19526
19527 return SDValue();
19528}
19529
19531 SelectionDAG &DAG) {
19532 SDLoc DL(Op);
19533 SDValue X = Op.getOperand(0);
19534 MVT XTy = X.getSimpleValueType();
19535 SDValue Exp = Op.getOperand(1);
19536
19537 switch (XTy.SimpleTy) {
19538 default:
19539 return SDValue();
19540 case MVT::f16:
19541 if (!Subtarget.hasFP16())
19542 X = DAG.getFPExtendOrRound(X, DL, MVT::f32);
19543 [[fallthrough]];
19544 case MVT::f32:
19545 case MVT::f64: {
19546 MVT VT = MVT::getVectorVT(X.getSimpleValueType(),
19547 128 / X.getSimpleValueType().getSizeInBits());
19548 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, X.getValueType(), Exp);
19549 SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, X);
19550 SDValue VExp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Exp);
19551 SDValue Scalefs = DAG.getNode(X86ISD::SCALEFS, DL, VT, VX, VExp);
19552 SDValue Final = DAG.getExtractVectorElt(DL, X.getValueType(), Scalefs, 0);
19553 return DAG.getFPExtendOrRound(Final, DL, XTy);
19554 }
19555 case MVT::v4f32:
19556 case MVT::v2f64:
19557 case MVT::v8f32:
19558 case MVT::v4f64:
19559 case MVT::v16f32:
19560 case MVT::v8f64:
19561 if (XTy.getSizeInBits() == 512 || Subtarget.hasVLX()) {
19562 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19563 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19564 }
19565 break;
19566 case MVT::v8f16:
19567 case MVT::v16f16:
19568 if (Subtarget.hasFP16()) {
19569 if (Subtarget.hasVLX()) {
19570 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19571 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19572 }
19573 break;
19574 }
19575 X = DAG.getFPExtendOrRound(X, DL, XTy.changeVectorElementType(MVT::f32));
19576 Exp = DAG.getSExtOrTrunc(Exp, DL,
19577 X.getSimpleValueType().changeTypeToInteger());
19578 break;
19579 case MVT::v32f16:
19580 if (Subtarget.hasFP16()) {
19581 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19582 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19583 }
19584 return splitVectorOp(Op, DAG, DL);
19585 }
19586 SDValue WideX = widenSubVector(X, true, Subtarget, DAG, DL, 512);
19587 // Widen Exp to the same *lane count* as WideX (not necessarily 512 bits) so
19588 // SINT_TO_FP has matching vector lengths. For wide f64 the int exponent
19589 // vector is narrower than 512 bits (e.g. v2i32 -> v8i32 to match v8f64).
19590 MVT WideExpVT =
19591 MVT::getVectorVT(Exp.getSimpleValueType().getVectorElementType(),
19593 SDValue WideExp = widenSubVector(WideExpVT, Exp, /*ZeroNewElements=*/true,
19594 Subtarget, DAG, DL);
19595 SDValue WideExpFp =
19596 DAG.getNode(ISD::SINT_TO_FP, DL, WideX.getValueType(), WideExp);
19597 SDValue Scalef =
19598 DAG.getNode(X86ISD::SCALEF, DL, WideX.getValueType(), WideX, WideExpFp);
19599 SDValue Final =
19600 DAG.getExtractSubvector(DL, X.getSimpleValueType(), Scalef, 0);
19601 return DAG.getFPExtendOrRound(Final, DL, XTy);
19602}
19603
19605 SelectionDAG &DAG) {
19606 SDLoc dl(Op);
19607 MVT OpVT = Op.getSimpleValueType();
19608
19609 // It's always cheaper to replace a xor+movd with xorps and simplifies further
19610 // combines.
19611 if (X86::isZeroNode(Op.getOperand(0)))
19612 return getZeroVector(OpVT, Subtarget, DAG, dl);
19613
19614 // If this is a 256-bit vector result, first insert into a 128-bit
19615 // vector and then insert into the 256-bit vector.
19616 if (!OpVT.is128BitVector()) {
19617 // Insert into a 128-bit vector.
19618 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
19620 OpVT.getVectorNumElements() / SizeFactor);
19621
19622 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
19623
19624 // Insert the 128-bit vector.
19625 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
19626 }
19627 assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
19628 "Expected an SSE type!");
19629
19630 // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
19631 // tblgen.
19632 if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
19633 return Op;
19634
19635 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
19636 return DAG.getBitcast(
19637 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
19638}
19639
19640// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
19641// simple superregister reference or explicit instructions to insert
19642// the upper bits of a vector.
19644 SelectionDAG &DAG) {
19645 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
19646
19647 return insert1BitVector(Op, DAG, Subtarget);
19648}
19649
19651 SelectionDAG &DAG) {
19652 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
19653 "Only vXi1 extract_subvectors need custom lowering");
19654
19655 SDLoc dl(Op);
19656 SDValue Vec = Op.getOperand(0);
19657 uint64_t IdxVal = Op.getConstantOperandVal(1);
19658
19659 if (IdxVal == 0) // the operation is legal
19660 return Op;
19661
19662 // Extend to natively supported kshift.
19663 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19664
19665 // Shift to the LSB.
19666 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19667 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19668
19669 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19670 DAG.getVectorIdxConstant(0, dl));
19671}
19672
19673// Returns the appropriate wrapper opcode for a global reference.
19674unsigned X86TargetLowering::getGlobalWrapperKind(
19675 const GlobalValue *GV, const unsigned char OpFlags) const {
19676 // References to absolute symbols are never PC-relative.
19677 if (GV && GV->isAbsoluteSymbolRef())
19678 return X86ISD::Wrapper;
19679
19680 // The following OpFlags under RIP-rel PIC use RIP.
19681 if (Subtarget.isPICStyleRIPRel() &&
19682 (OpFlags == X86II::MO_NO_FLAG || OpFlags == X86II::MO_COFFSTUB ||
19683 OpFlags == X86II::MO_DLLIMPORT))
19684 return X86ISD::WrapperRIP;
19685
19686 // GOTPCREL references must always use RIP.
19687 if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
19688 return X86ISD::WrapperRIP;
19689
19690 return X86ISD::Wrapper;
19691}
19692
19693// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19694// their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19695// one of the above mentioned nodes. It has to be wrapped because otherwise
19696// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19697// be used to form addressing mode. These wrapped nodes will be selected
19698// into MOV32ri.
19699SDValue
19700X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19701 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19702
19703 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19704 // global base reg.
19705 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19706
19707 auto PtrVT = getPointerTy(DAG.getDataLayout());
19709 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19710 SDLoc DL(CP);
19711 Result =
19712 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19713 // With PIC, the address is actually $g + Offset.
19714 if (OpFlag) {
19715 Result =
19716 DAG.getNode(ISD::ADD, DL, PtrVT,
19717 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19718 }
19719
19720 return Result;
19721}
19722
19723SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19724 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19725
19726 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19727 // global base reg.
19728 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19729
19730 EVT PtrVT = Op.getValueType();
19731 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19732 SDLoc DL(JT);
19733 Result =
19734 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19735
19736 // With PIC, the address is actually $g + Offset.
19737 if (OpFlag)
19738 Result =
19739 DAG.getNode(ISD::ADD, DL, PtrVT,
19740 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19741
19742 return Result;
19743}
19744
19745SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19746 SelectionDAG &DAG) const {
19747 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19748}
19749
19750SDValue
19751X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19752 // Create the TargetBlockAddressAddress node.
19753 unsigned char OpFlags =
19754 Subtarget.classifyBlockAddressReference();
19755 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19756 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19757 SDLoc dl(Op);
19758 EVT PtrVT = Op.getValueType();
19759 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19760 Result =
19761 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlags), dl, PtrVT, Result);
19762
19763 // With PIC, the address is actually $g + Offset.
19764 if (isGlobalRelativeToPICBase(OpFlags)) {
19765 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19766 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19767 }
19768
19769 return Result;
19770}
19771
19772/// Creates target global address or external symbol nodes for calls or
19773/// other uses.
19774SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19775 bool ForCall,
19776 bool *IsImpCall) const {
19777 // Unpack the global address or external symbol.
19778 SDLoc dl(Op);
19779 const GlobalValue *GV = nullptr;
19780 int64_t Offset = 0;
19781 const char *ExternalSym = nullptr;
19782 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19783 GV = G->getGlobal();
19784 Offset = G->getOffset();
19785 } else {
19786 const auto *ES = cast<ExternalSymbolSDNode>(Op);
19787 ExternalSym = ES->getSymbol();
19788 }
19789
19790 // Calculate some flags for address lowering.
19792 unsigned char OpFlags;
19793 if (ForCall)
19794 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19795 else
19796 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19797 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19798 bool NeedsLoad = isGlobalStubReference(OpFlags);
19799
19801 EVT PtrVT = Op.getValueType();
19803
19804 if (GV) {
19805 // Create a target global address if this is a global. If possible, fold the
19806 // offset into the global address reference. Otherwise, ADD it on later.
19807 // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19808 // allowed because if the address of foo is 0, the ELF R_X86_64_32
19809 // relocation will compute to a negative value, which is invalid.
19810 int64_t GlobalOffset = 0;
19811 if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19813 std::swap(GlobalOffset, Offset);
19814 }
19815 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19816 } else {
19817 // If this is not a global address, this must be an external symbol.
19818 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19819 }
19820
19821 // If this is a direct call, avoid the wrapper if we don't need to do any
19822 // loads or adds. This allows SDAG ISel to match direct calls.
19823 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19824 return Result;
19825
19826 // If Import Call Optimization is enabled and this is an imported function
19827 // then make a note of it and return the global address without wrapping.
19828 if (IsImpCall && (OpFlags == X86II::MO_DLLIMPORT) &&
19829 Mod.getModuleFlag("import-call-optimization")) {
19830 assert(ForCall && "Should only enable import call optimization if we are "
19831 "lowering a call");
19832 *IsImpCall = true;
19833 return Result;
19834 }
19835
19836 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19837
19838 // With PIC, the address is actually $g + Offset.
19839 if (HasPICReg) {
19840 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19841 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19842 }
19843
19844 // For globals that require a load from a stub to get the address, emit the
19845 // load.
19846 if (NeedsLoad)
19847 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19849
19850 // If there was a non-zero offset that we didn't fold, create an explicit
19851 // addition for it.
19852 if (Offset != 0)
19853 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19854 DAG.getSignedConstant(Offset, dl, PtrVT));
19855
19856 return Result;
19857}
19858
19859SDValue
19860X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19861 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19862}
19863
19865 const EVT PtrVT, unsigned ReturnReg,
19866 unsigned char OperandFlags,
19867 bool LoadGlobalBaseReg = false,
19868 bool LocalDynamic = false) {
19870 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19871 SDLoc dl(GA);
19872 SDValue TGA;
19873 bool UseTLSDESC = DAG.getTarget().useTLSDESC();
19874 SDValue Chain = DAG.getEntryNode();
19875 SDValue Ret;
19876 if (LocalDynamic && UseTLSDESC) {
19877 TGA = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, OperandFlags);
19878 // Reuse existing GetTLSADDR node if we can find it.
19879 if (TGA->hasOneUse()) {
19880 // TLSDESC uses TGA.
19881 SDNode *TLSDescOp = *TGA->user_begin();
19882 assert(TLSDescOp->getOpcode() == X86ISD::TLSDESC &&
19883 "Unexpected TLSDESC DAG");
19884 // CALLSEQ_END uses TGA via a chain and glue.
19885 auto *CallSeqEndOp = TLSDescOp->getGluedUser();
19886 assert(CallSeqEndOp && CallSeqEndOp->getOpcode() == ISD::CALLSEQ_END &&
19887 "Unexpected TLSDESC DAG");
19888 // CopyFromReg uses CALLSEQ_END via a chain and glue.
19889 auto *CopyFromRegOp = CallSeqEndOp->getGluedUser();
19890 assert(CopyFromRegOp && CopyFromRegOp->getOpcode() == ISD::CopyFromReg &&
19891 "Unexpected TLSDESC DAG");
19892 Ret = SDValue(CopyFromRegOp, 0);
19893 }
19894 } else {
19895 TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19896 GA->getOffset(), OperandFlags);
19897 }
19898
19899 if (!Ret) {
19900 unsigned CallType = UseTLSDESC ? X86ISD::TLSDESC
19901 : LocalDynamic ? X86ISD::TLSBASEADDR
19902 : X86ISD::TLSADDR;
19903
19904 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
19905 if (LoadGlobalBaseReg) {
19906 SDValue InGlue;
19907 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
19908 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT),
19909 InGlue);
19910 InGlue = Chain.getValue(1);
19911 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA, InGlue});
19912 } else {
19913 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA});
19914 }
19915 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), dl);
19916
19917 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19918 MFI.setHasCalls(true);
19919
19920 SDValue Glue = Chain.getValue(1);
19921 Ret = DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
19922 }
19923
19924 if (!UseTLSDESC)
19925 return Ret;
19926
19928 unsigned Seg = Subtarget.is64Bit() ? X86AS::FS : X86AS::GS;
19929
19931 SDValue Offset =
19932 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19933 MachinePointerInfo(Ptr));
19934 return DAG.getNode(ISD::ADD, dl, PtrVT, Ret, Offset);
19935}
19936
19937// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19938static SDValue
19940 const EVT PtrVT) {
19941 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD,
19942 /*LoadGlobalBaseReg=*/true);
19943}
19944
19945// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19946static SDValue
19948 const EVT PtrVT) {
19949 return GetTLSADDR(DAG, GA, PtrVT, X86::RAX, X86II::MO_TLSGD);
19950}
19951
19952// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19953static SDValue
19955 const EVT PtrVT) {
19956 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD);
19957}
19958
19960 SelectionDAG &DAG, const EVT PtrVT,
19961 bool Is64Bit, bool Is64BitLP64) {
19962 SDLoc dl(GA);
19963
19964 // Get the start address of the TLS block for this module.
19968
19969 SDValue Base;
19970 if (Is64Bit) {
19971 unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19972 Base = GetTLSADDR(DAG, GA, PtrVT, ReturnReg, X86II::MO_TLSLD,
19973 /*LoadGlobalBaseReg=*/false,
19974 /*LocalDynamic=*/true);
19975 } else {
19976 Base = GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSLDM,
19977 /*LoadGlobalBaseReg=*/true,
19978 /*LocalDynamic=*/true);
19979 }
19980
19981 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19982 // of Base.
19983
19984 // Build x@dtpoff.
19985 unsigned char OperandFlags = X86II::MO_DTPOFF;
19986 unsigned WrapperKind = X86ISD::Wrapper;
19987 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19988 GA->getValueType(0),
19989 GA->getOffset(), OperandFlags);
19990 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19991
19992 // Add x@dtpoff with the base.
19993 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19994}
19995
19996// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19998 const EVT PtrVT, TLSModel::Model model,
19999 bool is64Bit, bool isPIC) {
20000 SDLoc dl(GA);
20001
20002 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
20005
20006 SDValue ThreadPointer =
20007 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
20008 MachinePointerInfo(Ptr));
20009
20010 unsigned char OperandFlags = 0;
20011 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
20012 // initialexec.
20013 unsigned WrapperKind = X86ISD::Wrapper;
20014 if (model == TLSModel::LocalExec) {
20015 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
20016 } else if (model == TLSModel::InitialExec) {
20017 if (is64Bit) {
20018 OperandFlags = X86II::MO_GOTTPOFF;
20019 WrapperKind = X86ISD::WrapperRIP;
20020 } else {
20021 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
20022 }
20023 } else {
20024 llvm_unreachable("Unexpected model");
20025 }
20026
20027 // emit "addl x@ntpoff,%eax" (local exec)
20028 // or "addl x@indntpoff,%eax" (initial exec)
20029 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
20030 SDValue TGA =
20031 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
20032 GA->getOffset(), OperandFlags);
20033 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20034
20035 if (model == TLSModel::InitialExec) {
20036 if (isPIC && !is64Bit) {
20037 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
20038 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20039 Offset);
20040 }
20041
20042 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
20044 }
20045
20046 // The address of the thread local variable is the add of the thread
20047 // pointer with the offset of the variable.
20048 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
20049}
20050
20051SDValue
20052X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
20053
20054 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
20055
20056 if (DAG.getTarget().useEmulatedTLS())
20057 return LowerToTLSEmulatedModel(GA, DAG);
20058
20059 const GlobalValue *GV = GA->getGlobal();
20060 EVT PtrVT = Op.getValueType();
20061 bool PositionIndependent = isPositionIndependent();
20062
20063 if (Subtarget.isTargetELF()) {
20064 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
20065 // LFI does not support dlopen, so all TLS can be statically resolved. We
20066 // automatically upgrade dynamic models to InitialExec because the dynamic
20067 // TLS sequences are slower than necessary and interact poorly with LFI
20068 // rewriting combined with rewrites from linker relaxation.
20069 if (Subtarget.isLFI())
20070 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic)
20071 model = TLSModel::InitialExec;
20072 switch (model) {
20074 if (Subtarget.is64Bit()) {
20075 if (Subtarget.isTarget64BitLP64())
20076 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
20077 return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
20078 }
20079 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
20081 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
20082 Subtarget.isTarget64BitLP64());
20085 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
20086 PositionIndependent);
20087 }
20088 llvm_unreachable("Unknown TLS model.");
20089 }
20090
20091 if (Subtarget.isTargetDarwin()) {
20092 // Darwin only has one model of TLS. Lower to that.
20093 unsigned char OpFlag = 0;
20094 unsigned WrapperKind = 0;
20095
20096 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20097 // global base reg.
20098 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
20099 if (PIC32) {
20100 OpFlag = X86II::MO_TLVP_PIC_BASE;
20101 WrapperKind = X86ISD::Wrapper;
20102 } else {
20103 OpFlag = X86II::MO_TLVP;
20104 WrapperKind = X86ISD::WrapperRIP;
20105 }
20106 SDLoc DL(Op);
20108 GA->getValueType(0),
20109 GA->getOffset(), OpFlag);
20110 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
20111
20112 // With PIC32, the address is actually $g + Offset.
20113 if (PIC32)
20114 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
20115 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20116 Offset);
20117
20118 // Lowering the machine isd will make sure everything is in the right
20119 // location.
20120 SDValue Chain = DAG.getEntryNode();
20121 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20122 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
20123 SDValue Args[] = { Chain, Offset };
20124 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
20125 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
20126
20127 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
20128 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20129 MFI.setAdjustsStack(true);
20130
20131 // And our return value (tls address) is in the standard call return value
20132 // location.
20133 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
20134 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
20135 }
20136
20137 if (Subtarget.isOSWindows()) {
20138 // Just use the implicit TLS architecture
20139 // Need to generate something similar to:
20140 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
20141 // ; from TEB
20142 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
20143 // mov rcx, qword [rdx+rcx*8]
20144 // mov eax, .tls$:tlsvar
20145 // [rax+rcx] contains the address
20146 // Windows 64bit: gs:0x58
20147 // Windows 32bit: fs:__tls_array
20148
20149 SDLoc dl(GA);
20150 SDValue Chain = DAG.getEntryNode();
20151
20152 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
20153 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
20154 // use its literal value of 0x2C.
20156 Subtarget.is64Bit() ? PointerType::get(*DAG.getContext(), X86AS::GS)
20158
20159 SDValue TlsArray = Subtarget.is64Bit()
20160 ? DAG.getIntPtrConstant(0x58, dl)
20161 : (Subtarget.isTargetWindowsGNU()
20162 ? DAG.getIntPtrConstant(0x2C, dl)
20163 : DAG.getExternalSymbol("_tls_array", PtrVT));
20164
20165 SDValue ThreadPointer =
20166 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
20167
20168 SDValue res;
20170 res = ThreadPointer;
20171 } else {
20172 // Load the _tls_index variable
20173 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
20174 if (Subtarget.is64Bit())
20175 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
20176 MachinePointerInfo(), MVT::i32);
20177 else
20178 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
20179
20180 const DataLayout &DL = DAG.getDataLayout();
20181 SDValue Scale =
20182 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
20183 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
20184
20185 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
20186 }
20187
20188 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
20189
20190 // Get the offset of start of .tls section
20191 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20192 GA->getValueType(0),
20194 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
20195
20196 // The address of the thread local variable is the add of the thread
20197 // pointer with the offset of the variable.
20198 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
20199 }
20200
20201 llvm_unreachable("TLS not implemented for this target.");
20202}
20203
20205 if (Subtarget.is64Bit() && Subtarget.isTargetELF()) {
20206 const TargetMachine &TM = getTargetMachine();
20207 TLSModel::Model Model = TM.getTLSModel(&GV);
20208 switch (Model) {
20211 // We can include the %fs segment register in addressing modes.
20212 return true;
20215 // These models do not result in %fs relative addresses unless
20216 // TLS descriptior are used.
20217 //
20218 // Even in the case of TLS descriptors we currently have no way to model
20219 // the difference between %fs access and the computations needed for the
20220 // offset and returning `true` for TLS-desc currently duplicates both
20221 // which is detrimental :-/
20222 return false;
20223 }
20224 }
20225 return false;
20226}
20227
20228/// Lower SRA_PARTS and friends, which return two i32 values
20229/// and take a 2 x i32 value to shift plus a shift amount.
20230/// TODO: Can this be moved to general expansion code?
20232 SDValue Lo, Hi;
20233 DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
20234 return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
20235}
20236
20237// Try to use a packed vector operation to handle i64 on 32-bit targets when
20238// AVX512DQ is enabled.
20240 SelectionDAG &DAG,
20241 const X86Subtarget &Subtarget) {
20242 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20243 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20244 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20245 Op.getOpcode() == ISD::UINT_TO_FP) &&
20246 "Unexpected opcode!");
20247 bool IsStrict = Op->isStrictFPOpcode();
20248 unsigned OpNo = IsStrict ? 1 : 0;
20249 SDValue Src = Op.getOperand(OpNo);
20250 MVT SrcVT = Src.getSimpleValueType();
20251 MVT VT = Op.getSimpleValueType();
20252
20253 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
20254 (VT != MVT::f32 && VT != MVT::f64))
20255 return SDValue();
20256
20257 // Pack the i64 into a vector, do the operation and extract.
20258
20259 // Using 256-bit to ensure result is 128-bits for f32 case.
20260 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
20261 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
20262 MVT VecVT = MVT::getVectorVT(VT, NumElts);
20263
20264 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
20265 if (IsStrict) {
20266 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
20267 {Op.getOperand(0), InVec});
20268 SDValue Chain = CvtVec.getValue(1);
20269 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20270 DAG.getVectorIdxConstant(0, dl));
20271 return DAG.getMergeValues({Value, Chain}, dl);
20272 }
20273
20274 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
20275
20276 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20277 DAG.getVectorIdxConstant(0, dl));
20278}
20279
20280// Try to use a packed vector operation to handle i64 on 32-bit targets.
20282 const X86Subtarget &Subtarget) {
20283 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20284 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20285 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20286 Op.getOpcode() == ISD::UINT_TO_FP) &&
20287 "Unexpected opcode!");
20288 bool IsStrict = Op->isStrictFPOpcode();
20289 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20290 MVT SrcVT = Src.getSimpleValueType();
20291 MVT VT = Op.getSimpleValueType();
20292
20293 if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
20294 return SDValue();
20295
20296 // Pack the i64 into a vector, do the operation and extract.
20297
20298 assert(Subtarget.hasFP16() && "Expected FP16");
20299
20300 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
20301 if (IsStrict) {
20302 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
20303 {Op.getOperand(0), InVec});
20304 SDValue Chain = CvtVec.getValue(1);
20305 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20306 DAG.getVectorIdxConstant(0, dl));
20307 return DAG.getMergeValues({Value, Chain}, dl);
20308 }
20309
20310 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
20311
20312 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20313 DAG.getVectorIdxConstant(0, dl));
20314}
20315
20316static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
20317 const X86Subtarget &Subtarget) {
20318 switch (Opcode) {
20319 case ISD::SINT_TO_FP:
20320 // TODO: Handle wider types with AVX/AVX512.
20321 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
20322 return false;
20323 // CVTDQ2PS or (V)CVTDQ2PD
20324 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
20325
20326 case ISD::UINT_TO_FP:
20327 // TODO: Handle wider types and i64 elements.
20328 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
20329 return false;
20330 // VCVTUDQ2PS or VCVTUDQ2PD
20331 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
20332
20333 default:
20334 return false;
20335 }
20336}
20337
20338/// Given a scalar cast operation that is extracted from a vector, try to
20339/// vectorize the cast op followed by extraction. This will avoid an expensive
20340/// round-trip between XMM and GPR.
20342 SelectionDAG &DAG,
20343 const X86Subtarget &Subtarget) {
20344 // TODO: This could be enhanced to handle smaller integer types by peeking
20345 // through an extend.
20346 SDValue Extract = Cast.getOperand(0);
20347 MVT DestVT = Cast.getSimpleValueType();
20348 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20349 !isa<ConstantSDNode>(Extract.getOperand(1)))
20350 return SDValue();
20351
20352 // See if we have a 128-bit vector cast op for this type of cast.
20353 SDValue VecOp = Extract.getOperand(0);
20354 EVT FromVT = VecOp.getValueType();
20355 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
20356 MVT Vec128VT =
20357 MVT::getVectorVT(FromVT.getScalarType().getSimpleVT(), NumEltsInXMM);
20358 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
20359 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
20360 return SDValue();
20361
20362 // If we are extracting from a non-zero element, first shuffle the source
20363 // vector to allow extracting from element zero.
20364 if (!isNullConstant(Extract.getOperand(1))) {
20365 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
20366 Mask[0] = Extract.getConstantOperandVal(1);
20367 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
20368 }
20369 // If the source vector is wider than 128-bits, extract the low part. Do not
20370 // create an unnecessarily wide vector cast op.
20371 if (FromVT != Vec128VT)
20372 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
20373
20374 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
20375 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
20376 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
20377 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
20378 DAG.getVectorIdxConstant(0, DL));
20379}
20380
20381/// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
20382/// try to vectorize the cast ops. This will avoid an expensive round-trip
20383/// between XMM and GPR.
20384static SDValue lowerFPToIntToFP(SDValue CastToFP, const SDLoc &DL,
20385 SelectionDAG &DAG,
20386 const X86Subtarget &Subtarget) {
20387 SDValue CastToInt = CastToFP.getOperand(0);
20388 MVT VT = CastToFP.getSimpleValueType();
20389 if ((CastToFP.getOpcode() != ISD::SINT_TO_FP &&
20390 CastToFP.getOpcode() != ISD::UINT_TO_FP) ||
20391 (CastToInt.getOpcode() != ISD::FP_TO_SINT &&
20392 CastToInt.getOpcode() != ISD::FP_TO_UINT) ||
20393 VT.isVector())
20394 return SDValue();
20395
20396 MVT IntVT = CastToInt.getSimpleValueType();
20397 SDValue X = CastToInt.getOperand(0);
20398 MVT SrcVT = X.getSimpleValueType();
20399 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
20400 return SDValue();
20401
20402 // See if we have 128-bit vector cast instructions for this type of cast.
20403 // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
20404 if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
20405 (IntVT != MVT::i32 && IntVT != MVT::i64))
20406 return SDValue();
20407
20408 unsigned SrcSize = SrcVT.getSizeInBits();
20409 unsigned IntSize = IntVT.getSizeInBits();
20410 unsigned VTSize = VT.getSizeInBits();
20411 bool FromUnsigned = CastToFP.getOpcode() == ISD::UINT_TO_FP;
20412 bool ToUnsigned = CastToInt.getOpcode() == ISD::FP_TO_UINT;
20413 unsigned ToIntOpcode =
20414 SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
20415 unsigned ToFPOpcode =
20416 IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
20417 unsigned Width = 128;
20418
20419 if (Subtarget.hasVLX() && Subtarget.hasDQI()) {
20420 // AVX512DQ+VLX
20421 if (ToUnsigned) {
20422 ToIntOpcode =
20423 SrcSize != IntSize ? X86ISD::CVTTP2UI : (unsigned)ISD::FP_TO_UINT;
20424 }
20425 if (FromUnsigned) {
20426 ToFPOpcode =
20427 IntSize != VTSize ? X86ISD::CVTUI2P : (unsigned)ISD::UINT_TO_FP;
20428 }
20429 } else {
20430 if (FromUnsigned || ToUnsigned || IntVT == MVT::i64) {
20431 // SSE2 can only perform f64/f32 <-> i32 signed.
20432 if (!Subtarget.useAVX512Regs() || !Subtarget.hasDQI())
20433 return SDValue();
20434
20435 // Need to extend width for AVX512DQ without AVX512VL.
20436 Width = 512;
20437 ToIntOpcode = CastToInt.getOpcode();
20438 ToFPOpcode = FromUnsigned ? ISD::UINT_TO_FP : ISD::SINT_TO_FP;
20439 }
20440 }
20441
20442 MVT VecSrcVT, VecIntVT, VecVT;
20443 unsigned NumElts;
20444 unsigned SrcElts, VTElts;
20445 // Some conversions are only legal with uniform vector sizes on AVX512DQ.
20446 if (Width == 512) {
20447 NumElts = std::min(Width / IntSize, Width / SrcSize);
20448 SrcElts = NumElts;
20449 VTElts = NumElts;
20450 } else {
20451 NumElts = Width / IntSize;
20452 SrcElts = Width / SrcSize;
20453 VTElts = Width / VTSize;
20454 }
20455 VecIntVT = MVT::getVectorVT(IntVT, NumElts);
20456 VecSrcVT = MVT::getVectorVT(SrcVT, SrcElts);
20457 VecVT = MVT::getVectorVT(VT, VTElts);
20458 // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
20459 //
20460 // We are not defining the high elements (for example, zero them) because
20461 // that could nullify any performance advantage that we hoped to gain from
20462 // this vector op hack. We do not expect any adverse effects (like denorm
20463 // penalties) with cast ops.
20464 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
20465 SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
20466 SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
20467 SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
20468 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
20469}
20470
20472 SelectionDAG &DAG,
20473 const X86Subtarget &Subtarget) {
20474 bool IsStrict = Op->isStrictFPOpcode();
20475 MVT VT = Op->getSimpleValueType(0);
20476 SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
20477
20478 if (Subtarget.hasDQI()) {
20479 assert(!Subtarget.hasVLX() && "Unexpected features");
20480
20481 assert((Src.getSimpleValueType() == MVT::v2i64 ||
20482 Src.getSimpleValueType() == MVT::v4i64) &&
20483 "Unsupported custom type");
20484
20485 // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
20486 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
20487 "Unexpected VT!");
20488 MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20489
20490 // Need to concat with zero vector for strict fp to avoid spurious
20491 // exceptions.
20492 SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
20493 : DAG.getUNDEF(MVT::v8i64);
20494 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
20495 DAG.getVectorIdxConstant(0, DL));
20496 SDValue Res, Chain;
20497 if (IsStrict) {
20498 Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
20499 {Op->getOperand(0), Src});
20500 Chain = Res.getValue(1);
20501 } else {
20502 Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
20503 }
20504
20505 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20506 DAG.getVectorIdxConstant(0, DL));
20507
20508 if (IsStrict)
20509 return DAG.getMergeValues({Res, Chain}, DL);
20510 return Res;
20511 }
20512
20513 bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
20514 Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
20515 if (VT != MVT::v4f32 || IsSigned)
20516 return SDValue();
20517
20518 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
20519 SDValue One = DAG.getConstant(1, DL, MVT::v4i64);
20520 SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
20521 DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
20522 DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
20523 SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
20524 SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
20525 SmallVector<SDValue, 4> SignCvts(4);
20526 SmallVector<SDValue, 4> Chains(4);
20527 for (int i = 0; i != 4; ++i) {
20528 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
20529 DAG.getVectorIdxConstant(i, DL));
20530 if (IsStrict) {
20531 SignCvts[i] =
20532 DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
20533 {Op.getOperand(0), Elt});
20534 Chains[i] = SignCvts[i].getValue(1);
20535 } else {
20536 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
20537 }
20538 }
20539 SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
20540
20541 SDValue Slow, Chain;
20542 if (IsStrict) {
20543 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
20544 Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
20545 {Chain, SignCvt, SignCvt});
20546 Chain = Slow.getValue(1);
20547 } else {
20548 Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
20549 }
20550
20551 IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
20552 SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
20553
20554 if (IsStrict)
20555 return DAG.getMergeValues({Cvt, Chain}, DL);
20556
20557 return Cvt;
20558}
20559
20561 SelectionDAG &DAG) {
20562 bool IsStrict = Op->isStrictFPOpcode();
20563 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20564 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20565 MVT VT = Op.getSimpleValueType();
20566 MVT NVT = VT.changeElementType(MVT::f32);
20567
20568 SDValue Rnd = DAG.getIntPtrConstant(0, dl, /*isTarget=*/true);
20569 if (IsStrict)
20570 return DAG.getNode(
20571 ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
20572 {Chain,
20573 DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
20574 Rnd});
20575 return DAG.getNode(ISD::FP_ROUND, dl, VT,
20576 DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
20577}
20578
20579static bool isLegalConversion(MVT VT, MVT FloatVT, bool IsSigned,
20580 const X86Subtarget &Subtarget) {
20581 if (FloatVT.getScalarType() != MVT::f16 || Subtarget.hasVLX()) {
20582 if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
20583 return true;
20584 if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
20585 return true;
20586 }
20587 if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
20588 return true;
20589 if (Subtarget.useAVX512Regs()) {
20590 if (VT == MVT::v16i32)
20591 return true;
20592 if (VT == MVT::v8i64 && FloatVT == MVT::v8f16 && Subtarget.hasFP16())
20593 return true;
20594 if (VT == MVT::v8i64 && Subtarget.hasDQI())
20595 return true;
20596 }
20597 if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
20598 (VT == MVT::v2i64 || VT == MVT::v4i64))
20599 return true;
20600 return false;
20601}
20602
20603SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20604 SelectionDAG &DAG) const {
20605 bool IsStrict = Op->isStrictFPOpcode();
20606 unsigned OpNo = IsStrict ? 1 : 0;
20607 SDValue Src = Op.getOperand(OpNo);
20608 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20609 MVT SrcVT = Src.getSimpleValueType();
20610 MVT VT = Op.getSimpleValueType();
20611 SDLoc dl(Op);
20612
20613 if (isBF16orSoftF16(VT, Subtarget))
20614 return promoteXINT_TO_FP(Op, dl, DAG);
20615 else if (isLegalConversion(SrcVT, VT, true, Subtarget))
20616 return Op;
20617
20618 if (Subtarget.isCallingConvWin64(CallingConv::C) && SrcVT == MVT::i128)
20619 return LowerWin64_INT128_TO_FP(Op, DAG);
20620
20621 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
20622 return Extract;
20623
20624 if (SDValue R = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
20625 return R;
20626
20627 if (SrcVT.isVector()) {
20628 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
20629 // Note: Since v2f64 is a legal type. We don't need to zero extend the
20630 // source for strict FP.
20631 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20632 DAG.getUNDEF(SrcVT));
20633 if (IsStrict)
20634 return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
20635 {Chain, Src});
20636 return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Src);
20637 }
20638 if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
20639 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
20640
20641 return SDValue();
20642 }
20643
20644 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
20645 "Unknown SINT_TO_FP to lower!");
20646
20647 bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
20648
20649 // These are really Legal; return the operand so the caller accepts it as
20650 // Legal.
20651 if (SrcVT == MVT::i32 && UseSSEReg)
20652 return Op;
20653 if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
20654 return Op;
20655
20656 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
20657 return V;
20658 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
20659 return V;
20660
20661 // SSE doesn't have an i16 conversion so we need to promote.
20662 if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
20663 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
20664 if (IsStrict)
20665 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
20666 {Chain, Ext});
20667
20668 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
20669 }
20670
20671 if (VT == MVT::f128 || !Subtarget.hasX87())
20672 return SDValue();
20673
20674 SDValue ValueToStore = Src;
20675 if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
20676 // Bitcasting to f64 here allows us to do a single 64-bit store from
20677 // an SSE register, avoiding the store forwarding penalty that would come
20678 // with two 32-bit stores.
20679 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20680
20681 unsigned Size = SrcVT.getStoreSize();
20684 auto PtrVT = getPointerTy(MF.getDataLayout());
20685 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
20686 MachinePointerInfo MPI =
20688 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20689 Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
20690 std::pair<SDValue, SDValue> Tmp =
20691 BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
20692
20693 if (IsStrict)
20694 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20695
20696 return Tmp.first;
20697}