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"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/Intrinsics.h"
54#include "llvm/MC/MCAsmInfo.h"
55#include "llvm/MC/MCContext.h"
56#include "llvm/MC/MCExpr.h"
57#include "llvm/MC/MCSymbol.h"
58#include "llvm/Support/Debug.h"
63#include <algorithm>
64#include <bitset>
65#include <cctype>
66#include <list>
67#include <numeric>
68using namespace llvm;
69
70#define DEBUG_TYPE "x86-isel"
71
73 const X86Subtarget &STI)
74 : TargetLowering(TM, STI), Subtarget(STI) {
75 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
76 MVT PtrVT = Subtarget.isTarget64BitLP64() ? MVT::i64 : MVT::i32;
77
78 // Set up the TargetLowering object.
79
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84
85 // X86 instruction cache is coherent with its data cache so we can use the
86 // default expansion to a no-op.
88
89 // For 64-bit, since we have so many registers, use the ILP scheduler.
90 // For 32-bit, use the register pressure specific scheduling.
91 // For Atom, always use ILP scheduling.
92 if (Subtarget.isAtom())
94 else if (Subtarget.is64Bit())
96 else
98 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
99 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101 // Bypass expensive divides and use cheaper ones.
102 if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
103 if (Subtarget.hasSlowDivide32())
104 addBypassSlowDiv(32, 8);
105 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
106 addBypassSlowDiv(64, 32);
107 }
108
109 if (Subtarget.canUseCMPXCHG16B())
111 else if (Subtarget.canUseCMPXCHG8B())
113 else
115
116 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
117
119
120 // Set up the register classes.
121 addRegisterClass(MVT::i8, &X86::GR8RegClass);
122 addRegisterClass(MVT::i16, &X86::GR16RegClass);
123 addRegisterClass(MVT::i32, &X86::GR32RegClass);
124 if (Subtarget.is64Bit())
125 addRegisterClass(MVT::i64, &X86::GR64RegClass);
126
127 for (MVT VT : MVT::integer_valuetypes())
129
130 // We don't accept any truncstore of integer registers.
131 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
132 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
133 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
134 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
135 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
136 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
137
138 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
139
140 // SETOEQ and SETUNE require checking two conditions.
141 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
144 }
145
146 // Integer absolute.
147 if (Subtarget.canUseCMOV()) {
148 setOperationAction(ISD::ABS , MVT::i16 , Custom);
149 setOperationAction(ISD::ABS , MVT::i32 , Custom);
150 if (Subtarget.is64Bit())
151 setOperationAction(ISD::ABS , MVT::i64 , Custom);
152 }
153
154 // Absolute difference.
155 for (auto Op : {ISD::ABDS, ISD::ABDU}) {
156 setOperationAction(Op , MVT::i8 , Custom);
157 setOperationAction(Op , MVT::i16 , Custom);
158 setOperationAction(Op , MVT::i32 , Custom);
159 if (Subtarget.is64Bit())
160 setOperationAction(Op , MVT::i64 , Custom);
161 }
162
163 // Signed saturation subtraction.
167 if (Subtarget.is64Bit())
169
170 // Funnel shifts.
171 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
172 // For slow shld targets we only lower for code size.
173 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
174
175 setOperationAction(ShiftOp , MVT::i8 , Custom);
176 setOperationAction(ShiftOp , MVT::i16 , Custom);
177 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
178 if (Subtarget.is64Bit())
179 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
180 }
181
182 if (!Subtarget.useSoftFloat()) {
183 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
184 // operation.
189 // We have an algorithm for SSE2, and we turn this into a 64-bit
190 // FILD or VCVTUSI2SS/SD for other targets.
193 // We have an algorithm for SSE2->double, and we turn this into a
194 // 64-bit FILD followed by conditional FADD for other targets.
197
198 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
199 // this operation.
202 // SSE has no i16 to fp conversion, only i32. We promote in the handler
203 // to allow f80 to use i16 and f64 to use i16 with sse1 only
206 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
213
214 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215 // this operation.
217 // FIXME: This doesn't generate invalid exception when it should. PR44019.
223 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
224 // are Legal, f80 is custom lowered.
227
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
229 // conversion.
231 // FIXME: This doesn't generate invalid exception when it should. PR44019.
234 // FIXME: This doesn't generate invalid exception when it should. PR44019.
240
245
246 if (!Subtarget.is64Bit() && Subtarget.hasX87()) {
249 }
250 }
251
252 // Handle address space casts between mixed sized pointers.
255
256 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257 if (!Subtarget.hasSSE2()) {
260 if (Subtarget.is64Bit()) {
262 // Without SSE, i64->f64 goes through memory.
264 }
265 } else if (!Subtarget.is64Bit())
267
268 // Scalar integer divide and remainder are lowered to use operations that
269 // produce two results, to match the available instructions. This exposes
270 // the two-result form to trivial CSE, which is able to combine x/y and x%y
271 // into a single instruction.
272 //
273 // Scalar integer multiply-high is also lowered to use two-result
274 // operations, to match the available instructions. However, plain multiply
275 // (low) operations are left as Legal, as there are single-result
276 // instructions for this in x86. Using the two-result multiply instructions
277 // when both high and low results are needed must be arranged by dagcombine.
278 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
285 }
286
287 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
289 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
290 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
293 }
294 if (Subtarget.is64Bit())
299
304
305 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
311 }
312
313 // Promote the i8 variants and force them on up to i32 which has a shorter
314 // encoding.
315 setOperationPromotedToType(ISD::CTTZ, MVT::i8, MVT::i32);
317 // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
318 // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
319 // promote that too.
320 setOperationPromotedToType(ISD::CTTZ, MVT::i16, MVT::i32);
322
323 if (!Subtarget.hasBMI()) {
326 if (Subtarget.is64Bit()) {
329 }
330 }
331
332 if (Subtarget.hasLZCNT()) {
333 // When promoting the i8 variants, force them to i32 for a shorter
334 // encoding.
335 setOperationPromotedToType(ISD::CTLZ, MVT::i8, MVT::i32);
337 } else {
338 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
339 if (VT == MVT::i64 && !Subtarget.is64Bit())
340 continue;
343 }
344 }
345
348 // Special handling for half-precision floating point conversions.
349 // If we don't have F16C support, then lower half float conversions
350 // into library calls.
352 Op, MVT::f32,
353 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
354 // There's never any support for operations beyond MVT::f32.
355 setOperationAction(Op, MVT::f64, Expand);
356 setOperationAction(Op, MVT::f80, Expand);
357 setOperationAction(Op, MVT::f128, Expand);
358 }
359
360 for (auto VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
363 }
364
365 for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
366 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
367 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
368 setTruncStoreAction(VT, MVT::f16, Expand);
369 setTruncStoreAction(VT, MVT::bf16, Expand);
370
373 }
374
378 if (Subtarget.is64Bit())
380 if (Subtarget.hasPOPCNT()) {
381 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
382 // popcntw is longer to encode than popcntl and also has a false dependency
383 // on the dest that popcntl hasn't had since Cannon Lake.
384 setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
385 } else {
390 }
391
392 if (Subtarget.hasBMI2()) {
393 bool SlowPDEP = Subtarget.isPDEPSlow();
394 bool SlowPEXT = Subtarget.isPEXTSlow();
397 setOperationAction(ISD::PDEP, MVT::i32, SlowPDEP ? Custom : Legal);
398 setOperationAction(ISD::PEXT, MVT::i32, SlowPEXT ? Custom : Legal);
399 if (Subtarget.is64Bit()) {
400 setOperationAction(ISD::PDEP, MVT::i64, SlowPDEP ? Custom : Legal);
401 setOperationAction(ISD::PEXT, MVT::i64, SlowPEXT ? Custom : Legal);
402 }
403 }
404
406
407 if (!Subtarget.hasMOVBE())
409
410 // X86 wants to expand cmov itself.
411 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
416 }
417 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
418 if (VT == MVT::i64 && !Subtarget.is64Bit())
419 continue;
422 }
423
425
426 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
429
431 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
432 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
436
437 // Darwin ABI issue.
438 for (auto VT : { MVT::i32, MVT::i64 }) {
439 if (VT == MVT::i64 && !Subtarget.is64Bit())
440 continue;
447 }
448
449 // 64-bit shl, sra, srl (iff 32-bit x86)
450 for (auto VT : { MVT::i32, MVT::i64 }) {
451 if (VT == MVT::i64 && !Subtarget.is64Bit())
452 continue;
456 }
457
458 if (Subtarget.hasSSEPrefetch())
460
462
463 // Expand certain atomics
464 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
472 }
473
474 if (!Subtarget.is64Bit())
476
477 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
478 // All CPUs supporting AVX will atomically load/store aligned 128-bit
479 // values, so we can emit [V]MOVAPS/[V]MOVDQA.
482 }
483
484 if (Subtarget.canUseCMPXCHG16B())
486
489
492
493 setOperationAction(ISD::TRAP, MVT::Other, Legal);
495 if (Subtarget.isTargetPS())
497 else
499
500 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
502 setOperationAction(ISD::VAEND , MVT::Other, Expand);
503 bool Is64Bit = Subtarget.is64Bit();
504 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
505 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
506
509
511
512 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
515
517
518 auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
519 setOperationAction(ISD::FABS, VT, Action);
520 setOperationAction(ISD::FNEG, VT, Action);
522 setOperationAction(ISD::FREM, VT, Action);
523 setOperationAction(ISD::FMA, VT, Action);
524 setOperationAction(ISD::FMINNUM, VT, Action);
525 setOperationAction(ISD::FMAXNUM, VT, Action);
530 setOperationAction(ISD::FSIN, VT, Action);
531 setOperationAction(ISD::FCOS, VT, Action);
532 setOperationAction(ISD::FSINCOS, VT, Action);
533 setOperationAction(ISD::FTAN, VT, Action);
534 setOperationAction(ISD::FSQRT, VT, Action);
535 setOperationAction(ISD::FPOW, VT, Action);
536 setOperationAction(ISD::FPOWI, VT, Action);
537 setOperationAction(ISD::FLOG, VT, Action);
538 setOperationAction(ISD::FLOG2, VT, Action);
539 setOperationAction(ISD::FLOG10, VT, Action);
540 setOperationAction(ISD::FEXP, VT, Action);
541 setOperationAction(ISD::FEXP2, VT, Action);
542 setOperationAction(ISD::FEXP10, VT, Action);
543 setOperationAction(ISD::FCEIL, VT, Action);
544 setOperationAction(ISD::FFLOOR, VT, Action);
546 setOperationAction(ISD::FRINT, VT, Action);
547 setOperationAction(ISD::BR_CC, VT, Action);
548 setOperationAction(ISD::SETCC, VT, Action);
551 setOperationAction(ISD::FROUND, VT, Action);
553 setOperationAction(ISD::FTRUNC, VT, Action);
554 setOperationAction(ISD::FLDEXP, VT, Action);
555 setOperationAction(ISD::FFREXP, VT, Action);
557 };
558
559 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
560 // f16, f32 and f64 use SSE.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
563 : &X86::FR16RegClass);
564 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
565 : &X86::FR32RegClass);
566 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
567 : &X86::FR64RegClass);
568
569 // Disable f32->f64 extload as we can only generate this in one instruction
570 // under optsize. So its easier to pattern match (fpext (load)) for that
571 // case instead of needing to emit 2 instructions for extload in the
572 // non-optsize case.
573 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
574
575 for (auto VT : { MVT::f32, MVT::f64 }) {
576 // Use ANDPD to simulate FABS.
578
579 // Use XORP to simulate FNEG.
581
582 // Use ANDPD and ORPD to simulate FCOPYSIGN.
584
585 // These might be better off as horizontal vector ops.
588
589 // We don't support sin/cos/fmod
593 }
594
595 // Half type will be promoted by default.
596 setF16Action(MVT::f16, Promote);
607
637
642
647
650
651 // Lower this to MOVMSK plus an AND.
654
655 } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
656 (UseX87 || Is64Bit)) {
657 // Use SSE for f32, x87 for f64.
658 // Set up the FP register classes.
659 addRegisterClass(MVT::f32, &X86::FR32RegClass);
660 if (UseX87)
661 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
662
663 // Use ANDPS to simulate FABS.
665
666 // Use XORP to simulate FNEG.
668
669 if (UseX87)
671
672 // Use ANDPS and ORPS to simulate FCOPYSIGN.
673 if (UseX87)
676
677 // We don't support sin/cos/fmod
681
682 if (UseX87) {
683 // Always expand sin/cos functions even though x87 has an instruction.
687 }
688 } else if (UseX87) {
689 // f32 and f64 in x87.
690 // Set up the FP register classes.
691 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
692 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
693
694 for (auto VT : { MVT::f32, MVT::f64 }) {
697
698 // Always expand sin/cos functions even though x87 has an instruction.
702 }
703 }
704
705 // Expand FP32 immediates into loads from the stack, save special cases.
706 if (isTypeLegal(MVT::f32)) {
707 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
708 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
709 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
710 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
711 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
712 } else // SSE immediates.
713 addLegalFPImmediate(APFloat(+0.0f)); // xorps
714 }
715 // Expand FP64 immediates into loads from the stack, save special cases.
716 if (isTypeLegal(MVT::f64)) {
717 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
718 addLegalFPImmediate(APFloat(+0.0)); // FLD0
719 addLegalFPImmediate(APFloat(+1.0)); // FLD1
720 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
721 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
722 } else // SSE immediates.
723 addLegalFPImmediate(APFloat(+0.0)); // xorpd
724 }
725 // Support fp16 0 immediate.
726 if (isTypeLegal(MVT::f16))
727 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
728
729 // Handle constrained floating-point operations of scalar.
742
743 // We don't support FMA.
746
747 // f80 always uses X87.
748 if (UseX87) {
749 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
752 {
754 addLegalFPImmediate(TmpFlt); // FLD0
755 TmpFlt.changeSign();
756 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
757
758 bool ignored;
759 APFloat TmpFlt2(+1.0);
761 &ignored);
762 addLegalFPImmediate(TmpFlt2); // FLD1
763 TmpFlt2.changeSign();
764 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
765 }
766
767 // Always expand sin/cos functions even though x87 has an instruction.
768 // clang-format off
780 // clang-format on
781
793
794 // Handle constrained floating-point operations of scalar.
801 if (isTypeLegal(MVT::f16)) {
804 } else {
806 }
807 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
808 // as Custom.
810 }
811
812 // f128 uses xmm registers, but most operations require libcalls.
813 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
814 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
815 : &X86::VR128RegClass);
816
817 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
818
829
833
834 // clang-format off
842 // clang-format on
843 // No STRICT_FSINCOS
846
849 // We need to custom handle any FP_ROUND with an f128 input, but
850 // LegalizeDAG uses the result type to know when to run a custom handler.
851 // So we have to list all legal floating point result types here.
852 if (isTypeLegal(MVT::f32)) {
855 }
856 if (isTypeLegal(MVT::f64)) {
859 }
860 if (isTypeLegal(MVT::f80)) {
864 }
865
867
868 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
869 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
870 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
871 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
872 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
873 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
874 }
875
876 // Always use a library call for pow.
877 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
878 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
879 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
880 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
881
890
891 // Some FP actions are always expanded for vector types.
892 for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
893 MVT::v4f32, MVT::v8f32, MVT::v16f32,
894 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
895 // clang-format off
909 // clang-format on
910 }
911
912 // First set operation action for all vector types to either promote
913 // (for widening) or expand (for scalarization). Then we will selectively
914 // turn on ones that can be effectively codegen'd.
954 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
955 setTruncStoreAction(InnerVT, VT, Expand);
956
959
960 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
961 // types, we have to deal with them whether we ask for Expansion or not.
962 // Setting Expand causes its own optimisation problems though, so leave
963 // them legal.
964 if (VT.getVectorElementType() == MVT::i1)
965 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
966
967 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
968 // split/scalarized right now.
969 if (VT.getVectorElementType() == MVT::f16 ||
970 VT.getVectorElementType() == MVT::bf16)
971 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
972 }
973 }
974
975 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
976 // with -msoft-float, disable use of MMX as well.
977 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
978 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
979 // No operations on x86mmx supported, everything uses intrinsics.
980 }
981
982 auto SetFPMinMaxAction = [&](MVT VT) {
991 };
992
993 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
994 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
995 : &X86::VR128RegClass);
996
997 SetFPMinMaxAction(MVT::f32);
998
999 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
1000 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
1008
1009 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
1010 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
1012
1018 }
1019
1020 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1021 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1022 : &X86::VR128RegClass);
1023
1024 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1025 // registers cannot be used even for integer operations.
1026 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1027 : &X86::VR128RegClass);
1028 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1029 : &X86::VR128RegClass);
1030 addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1031 : &X86::VR128RegClass);
1032 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1033 : &X86::VR128RegClass);
1034 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1035 : &X86::VR128RegClass);
1036
1037 for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 })
1038 SetFPMinMaxAction(VT);
1039
1040 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
1041 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
1042 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
1043
1044 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1045 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
1048 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
1049 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
1050 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
1051 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
1052 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
1053 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1056
1057 if (!Subtarget.is64Bit()) {
1058 setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1059 setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1060 }
1061
1062 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
1063 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
1064 setOperationAction(ISD::UMULO, MVT::v2i32, Custom);
1065
1066 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
1068 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
1070
1071 setOperationAction(ISD::LRINT, MVT::v4f32, Custom);
1072 setOperationAction(ISD::LRINT, MVT::v2i32, Custom);
1073
1074 setOperationAction(ISD::AND, MVT::i128, Custom);
1075 setOperationAction(ISD::OR, MVT::i128, Custom);
1076 setOperationAction(ISD::XOR, MVT::i128, Custom);
1078
1079 if (Subtarget.hasPCLMUL()) {
1080 for (auto VT : {MVT::i64, MVT::v4i32, MVT::v2i64}) {
1083 }
1087 }
1088
1089 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1090 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1091 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1092 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1093 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1094 }
1095
1096 // SSE2 can use basic vector unrolling.
1097 // SSE41 can use PHMINPOS to perform v16i8/v8i16 minmax reductions.
1098 // Fallback to ReplaceNodeResults for vXi64 reductions on 32-bit targets.
1099 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::i64}) {
1108 }
1109
1120
1125
1126 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1132
1133 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1134 // setcc all the way to isel and prefer SETGT in some isel patterns.
1137 }
1138
1139 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
1140 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
1145
1146 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1152 }
1153
1154 for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1158
1159 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1160 continue;
1161
1164 }
1165 setF16Action(MVT::v8f16, Expand);
1166 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1167 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1168 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1169 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1170 setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1171 setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1173
1174 // Custom lower v2i64 and v2f64 selects.
1181
1188
1189 // Custom legalize these to avoid over promotion or custom promotion.
1190 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1195 }
1196
1197 // Custom lowering for saturating float to int conversions.
1198 // We handle promotion to larger result types manually.
1199 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
1200 if (VT == MVT::i64 && !Subtarget.is64Bit())
1201 continue;
1204 }
1205
1210
1213
1216
1217 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1222
1227
1228 // We want to legalize this to an f64 load rather than an i64 load on
1229 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1230 // store.
1231 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1232 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1233 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1234 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1235 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1237
1238 // Add 32-bit vector stores to help vectorization opportunities.
1239 setOperationAction(ISD::STORE, MVT::v2i16, Custom);
1241
1245 if (!Subtarget.hasAVX512())
1247
1251
1253
1270
1271 // In the customized shift lowering, the legal v4i32/v2i64 cases
1272 // in AVX2 will be recognized.
1273 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1277 if (VT == MVT::v2i64) continue;
1282 }
1283
1289 }
1290
1291 if (!Subtarget.useSoftFloat() && Subtarget.hasGFNI()) {
1296
1297 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1299 }
1300
1301 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1302 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
1303 }
1304
1305 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1306 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1307 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1308 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1309
1310 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1313 }
1315
1316 // These might be better off as horizontal vector ops.
1321 }
1322 if (Subtarget.hasNDD()) {
1323 // Enable custom lowering for scalar USUBSAT to optimize usub.sat(X,1)
1324 // with cmp+adc when NDD is available.
1329 }
1330 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1331 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1334 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1338 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1344
1346 }
1347
1348 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1349 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1350 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1351 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1352 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1353 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1354 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1355 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1356
1360
1361 // FIXME: Do we need to handle scalar-to-vector here?
1362 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1363 setOperationAction(ISD::SMULO, MVT::v2i32, Custom);
1364
1365 // We directly match byte blends in the backend as they match the VSELECT
1366 // condition form.
1368
1369 // SSE41 brings specific instructions for doing vector sign extend even in
1370 // cases where we don't have SRA.
1371 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1374 }
1375
1376 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1377 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1378 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1379 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1380 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1381 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1382 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1383 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1384 }
1385
1386 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1387 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1388 // do the pre and post work in the vector domain.
1391 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1392 // so that DAG combine doesn't try to turn it into uint_to_fp.
1395 }
1396 }
1397
1398 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1400 }
1401
1402 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1403 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1404 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1407 }
1408
1409 // XOP can efficiently perform BITREVERSE with VPPERM.
1410 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1412 }
1413
1414 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1415 bool HasInt256 = Subtarget.hasInt256();
1416
1417 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1418 : &X86::VR256RegClass);
1419 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1420 : &X86::VR256RegClass);
1421 addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1422 : &X86::VR256RegClass);
1423 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1424 : &X86::VR256RegClass);
1425 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1426 : &X86::VR256RegClass);
1427 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1428 : &X86::VR256RegClass);
1429 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1430 : &X86::VR256RegClass);
1431
1432 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1445
1447
1452 SetFPMinMaxAction(VT);
1453 }
1454
1455 setOperationAction(ISD::LRINT, MVT::v8f32, Custom);
1456 setOperationAction(ISD::LRINT, MVT::v4f64, Custom);
1457
1458 setOperationAction(ISD::AND, MVT::i256, Custom);
1459 setOperationAction(ISD::OR, MVT::i256, Custom);
1460 setOperationAction(ISD::XOR, MVT::i256, Custom);
1463
1464 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1465 // even though v8i16 is a legal type.
1466 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1467 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1468 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1469 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1473
1480
1492
1493 if (!Subtarget.hasAVX512())
1495
1496 // In the customized shift lowering, the legal v8i32/v4i64 cases
1497 // in AVX2 will be recognized.
1498 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1512 if (VT == MVT::v4i64) continue;
1517 }
1518
1519 // These types need custom splitting if their input is a 128-bit vector.
1524
1528 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1529 setOperationAction(ISD::SELECT, MVT::v16f16, Custom);
1532
1533 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1537 }
1538
1543
1544 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1549
1550 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1551 // setcc all the way to isel and prefer SETGT in some isel patterns.
1554 }
1555
1556 setOperationAction(ISD::SETCC, MVT::v4f64, Custom);
1557 setOperationAction(ISD::SETCC, MVT::v8f32, Custom);
1562
1563 if (Subtarget.hasAnyFMA()) {
1564 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1565 MVT::v2f64, MVT::v4f64 }) {
1568 }
1569 }
1570
1571 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1572 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1573 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1574 }
1575
1576 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1577 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1578 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1579 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1580
1581 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1582 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1583 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1584 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1585 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1586 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1587 setOperationAction(ISD::AVGCEILU, MVT::v16i16, HasInt256 ? Legal : Custom);
1588 setOperationAction(ISD::AVGCEILU, MVT::v32i8, HasInt256 ? Legal : Custom);
1589
1590 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1591 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1592
1593 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1594 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1595 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1596 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1597 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1598
1599 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1600 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1601 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1602 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1603 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1604 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1605 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1606 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1611
1612 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1613 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1614 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1615 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1616 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1617 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1618 }
1619
1620 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1623 }
1624
1625 if (HasInt256) {
1626 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1627 // when we have a 256bit-wide blend with immediate.
1630
1631 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1632 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1633 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1634 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1635 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1636 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1637 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1638 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1639 }
1640 }
1641
1642 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1643 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1644 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1646 }
1647
1648 // Extract subvector is special because the value type
1649 // (result) is 128-bit but the source is 256-bit wide.
1650 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1651 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1653 }
1654
1655 // Custom lower several nodes for 256-bit types.
1656 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1657 MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1667 }
1668 setF16Action(MVT::v16f16, Expand);
1669 setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1670 setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1672 setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1673 setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1674 setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1675 setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1676
1677 // Only PCLMUL required as we always unroll clmul vectors.
1678 if (Subtarget.hasPCLMUL()) {
1679 for (auto VT : {MVT::v8i32, MVT::v4i64}) {
1682 }
1683 }
1684
1685 if (HasInt256) {
1686 setOperationAction(ISD::MULHU, MVT::v4i64, Custom);
1687 // Custom so the combiner keeps full products as [SU]MUL_LOHI, not
1688 // MULH[SU]. The custom lowering unrolls to scalar i64 [SU]MUL_LOHI,
1689 // which is only legalizable when i64 is a legal type.
1690 if (Subtarget.is64Bit()) {
1693 } else {
1694 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
1695 }
1697
1698 // Custom legalize 2x32 to get a little better code.
1701
1702 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1703 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1705
1706 // Custom PDEP/PEXT lowering to only scalarize for minsize.
1707 if (Subtarget.hasBMI2() && Subtarget.isPDEPSlow())
1708 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
1710
1711 if (Subtarget.hasBMI2() && Subtarget.isPEXTSlow())
1712 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
1714 }
1715
1716 if (Subtarget.hasGFNI()) {
1717 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1718 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1719 }
1720 }
1721
1722 if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1723 Subtarget.hasF16C()) {
1724 for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1727 }
1728 for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1731 }
1732 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1733 setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1734 setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1735 }
1736 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
1737 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
1738 }
1739
1740 // This block controls legalization of the mask vector sizes that are
1741 // available with AVX512. 512-bit vectors are in a separate block controlled
1742 // by useAVX512Regs.
1743 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1744 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1745 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1746 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1747 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1748 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1749
1753
1754 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1755 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1756 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1757 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1758 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1759 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1760 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1761 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1769
1770 // There is no byte sized k-register load or store without AVX512DQ.
1771 if (!Subtarget.hasDQI()) {
1772 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1773 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1774 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1775 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1776
1781 }
1782
1783 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1784 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1788 }
1789
1790 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1792
1793 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1797
1804 }
1805
1806 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1808 }
1809 if (Subtarget.hasDQI() && Subtarget.hasVLX()) {
1810 for (MVT VT : {MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1813 }
1814 }
1815
1816 // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1817 // elements. 512-bits can be disabled based on prefer-vector-width and
1818 // required-vector-width function attributes.
1819 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1820 bool HasBWI = Subtarget.hasBWI();
1821
1822 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1823 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1824 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1825 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1826 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1827 addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1828 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1829
1830 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1831 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1832 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1833 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1834 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1835 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1836 if (HasBWI)
1837 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1838 }
1839
1840 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1841 SetFPMinMaxAction(VT);
1849 }
1850 setOperationAction(ISD::LRINT, MVT::v16f32,
1851 Subtarget.hasDQI() ? Legal : Custom);
1852 setOperationAction(ISD::LRINT, MVT::v8f64,
1853 Subtarget.hasDQI() ? Legal : Custom);
1854 if (Subtarget.hasDQI())
1855 setOperationAction(ISD::LLRINT, MVT::v8f64, Legal);
1856
1857 setOperationAction(ISD::AND, MVT::i512, Custom);
1858 setOperationAction(ISD::OR, MVT::i512, Custom);
1859 setOperationAction(ISD::XOR, MVT::i512, Custom);
1860 setOperationAction(ISD::ADD, MVT::i512, Custom);
1861 setOperationAction(ISD::SUB, MVT::i512, Custom);
1862 setOperationAction(ISD::SRL, MVT::i512, Custom);
1863 setOperationAction(ISD::SHL, MVT::i512, Custom);
1864 setOperationAction(ISD::SRA, MVT::i512, Custom);
1865 setOperationAction(ISD::FSHR, MVT::i512, Custom);
1866 setOperationAction(ISD::FSHL, MVT::i512, Custom);
1867 setOperationAction(ISD::FSHR, MVT::i256, Custom);
1868 setOperationAction(ISD::FSHL, MVT::i256, Custom);
1871
1872 for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1877 }
1878
1879 for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1884 }
1885
1892
1904
1905 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1906 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1907 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1908 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1909 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1910 if (HasBWI)
1911 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1912
1913 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1914 // to 512-bit rather than use the AVX2 instructions so that we can use
1915 // k-masks.
1916 if (!Subtarget.hasVLX()) {
1917 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1918 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1921 }
1922 }
1923
1925 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1926 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
1936
1937 if (HasBWI) {
1938 // Extends from v64i1 masks to 512-bit vectors.
1942 }
1943
1944 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1957
1959 }
1960
1961 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1964 }
1965
1966 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1967 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1968 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
1969 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
1970
1971 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1972 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1973 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1974 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1975
1976 setOperationAction(ISD::MULHU, MVT::v8i64, Custom);
1977 setOperationAction(ISD::MULHS, MVT::v8i64, Custom);
1978 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1979 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1980 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1981 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1982 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1983 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1984 setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1985 setOperationAction(ISD::AVGCEILU, MVT::v64i8, HasBWI ? Legal : Custom);
1986
1987 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1988 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1989
1990 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
2008
2009 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
2010 // setcc all the way to isel and prefer SETGT in some isel patterns.
2013 }
2014
2015 setOperationAction(ISD::SETCC, MVT::v8f64, Custom);
2016 setOperationAction(ISD::SETCC, MVT::v16f32, Custom);
2021
2022 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
2031 }
2032
2033 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2034 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
2035 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
2037 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
2038 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
2039 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
2040 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
2045 }
2046
2047 setOperationAction(ISD::FSHL, MVT::v64i8, Custom);
2048 setOperationAction(ISD::FSHR, MVT::v64i8, Custom);
2049 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
2050 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
2051 setOperationAction(ISD::FSHL, MVT::v16i32, Custom);
2052 setOperationAction(ISD::FSHR, MVT::v16i32, Custom);
2053
2054 if (Subtarget.hasDQI() || Subtarget.hasFP16())
2058 setOperationAction(Opc, MVT::v8i64, Custom);
2059
2060 if (Subtarget.hasDQI()) {
2061 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
2062 }
2063
2064 if (Subtarget.hasCDI()) {
2065 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
2066 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
2068 }
2069 } // Subtarget.hasCDI()
2070
2071 if (Subtarget.hasVPOPCNTDQ()) {
2072 for (auto VT : { MVT::v16i32, MVT::v8i64 })
2075 }
2076
2077 // Extract subvector is special because the value type
2078 // (result) is 256-bit but the source is 512-bit wide.
2079 // 128-bit was made Legal under AVX1.
2080 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
2081 MVT::v16f16, MVT::v8f32, MVT::v4f64 })
2083
2084 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
2085 MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
2095 }
2096 setF16Action(MVT::v32f16, Expand);
2101 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2102 setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
2103 setOperationAction(ISD::SETCC, MVT::v32f16, Custom);
2104
2105 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
2110 }
2111 if (HasBWI) {
2112 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2115 }
2116 } else {
2117 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
2118 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
2119 }
2120
2121 if (Subtarget.hasVBMI2()) {
2122 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2125 }
2126
2127 setOperationAction(ISD::ROTL, MVT::v32i16, Legal);
2128 setOperationAction(ISD::ROTR, MVT::v32i16, Legal);
2129 }
2130
2131 // Only PCLMUL required as we always unroll clmul vectors.
2132 if (Subtarget.hasPCLMUL()) {
2133 for (auto VT : {MVT::v16i32, MVT::v8i64}) {
2136 }
2137 }
2138
2139 setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2140 setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2142 setOperationAction(ISD::FLDEXP, MVT::v32f16, Custom);
2143
2144 if (Subtarget.hasGFNI()) {
2145 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
2146 setOperationAction(ISD::CTTZ, MVT::v64i8, Custom);
2147 }
2148 }// useAVX512Regs
2149
2150 if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
2151 for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
2152 MVT::v4i64}) {
2155 }
2156
2157 setOperationAction(ISD::ROTL, MVT::v16i16, Legal);
2158 setOperationAction(ISD::ROTR, MVT::v16i16, Legal);
2159 setOperationAction(ISD::ROTL, MVT::v8i16, Legal);
2160 setOperationAction(ISD::ROTR, MVT::v8i16, Legal);
2161 }
2162
2163 // This block controls legalization for operations that don't have
2164 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2165 // narrower widths.
2166 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2167 for (MVT VT : {MVT::f16, MVT::f32, MVT::f64, MVT::v8f16, MVT::v4f32,
2168 MVT::v2f64, MVT::v16f16, MVT::v8f32, MVT::v4f64})
2170
2171 // These operations are handled on non-VLX by artificially widening in
2172 // isel patterns.
2176
2177 if (Subtarget.hasDQI()) {
2178 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2179 // v2f32 UINT_TO_FP is already custom under SSE2.
2182 "Unexpected operation action!");
2183 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2188 }
2189
2190 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2196 }
2197
2198 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2201 }
2202
2203 // Custom legalize 2x32 to get a little better code.
2206
2207 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2208 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2210
2211 if (Subtarget.hasDQI()) {
2215 setOperationAction(Opc, MVT::v2i64, Custom);
2216 setOperationAction(Opc, MVT::v4i64, Custom);
2217 }
2218 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2219 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2220
2221 // MULHS is only a win when the low multiply can use vpmullq; non-VLX
2222 // targets handle VPMULLQ by implicit widening.
2223 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
2224 }
2225
2226 if (Subtarget.hasCDI()) {
2227 for (auto VT : {MVT::i256, MVT::i512}) {
2228 if (VT == MVT::i512 && !Subtarget.useAVX512Regs())
2229 continue;
2234 }
2235 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2237 }
2238 } // Subtarget.hasCDI()
2239
2240 if (Subtarget.hasVPOPCNTDQ()) {
2241 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
2244 }
2245
2246 // We can try to convert vectors to different sizes to leverage legal
2247 // `vpcompress` cases. So we mark these supported vector sizes as Custom and
2248 // then specialize to Legal below.
2249 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2250 MVT::v4f64, MVT::v2i64, MVT::v2f64, MVT::v16i8, MVT::v8i16,
2251 MVT::v16i16, MVT::v8i8})
2253
2254 // Legal vpcompress depends on various AVX512 extensions.
2255 // Legal in AVX512F
2256 for (MVT VT : {MVT::v16i32, MVT::v16f32, MVT::v8i64, MVT::v8f64})
2258
2259 // Legal in AVX512F + AVX512VL
2260 if (Subtarget.hasVLX())
2261 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2262 MVT::v4f64, MVT::v2i64, MVT::v2f64})
2264
2265 // Legal in AVX512F + AVX512VBMI2
2266 if (Subtarget.hasVBMI2())
2267 for (MVT VT : {MVT::v32i16, MVT::v64i8})
2269
2270 // Legal in AVX512F + AVX512VL + AVX512VBMI2
2271 if (Subtarget.hasVBMI2() && Subtarget.hasVLX())
2272 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v32i8, MVT::v16i16})
2274 }
2275
2276 // This block control legalization of v32i1/v64i1 which are available with
2277 // AVX512BW..
2278 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2279 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
2280 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
2281
2282 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2293 }
2294
2295 for (auto VT : { MVT::v16i1, MVT::v32i1 })
2297
2298 // Extends from v32i1 masks to 256-bit vectors.
2302
2303 for (auto VT : {MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16,
2304 MVT::v16f16, MVT::v8f16}) {
2305 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
2306 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2307 }
2308
2309 // These operations are handled on non-VLX by artificially widening in
2310 // isel patterns.
2311 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2312
2313 if (Subtarget.hasBITALG()) {
2314 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2316 }
2317
2318 if (Subtarget.hasBMM()) {
2323
2324 for (auto VT : {MVT::v16i8, MVT::v32i8, MVT::v64i8})
2326 }
2327 }
2328
2329 if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2330 auto setGroup = [&] (MVT VT) {
2341
2354
2356
2359
2365
2371
2375 };
2376
2377 // AVX512_FP16 scalar operations
2378 setGroup(MVT::f16);
2379 SetFPMinMaxAction(MVT::f16);
2393
2396
2397 if (Subtarget.useAVX512Regs()) {
2398 setGroup(MVT::v32f16);
2404 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Legal);
2411
2416 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i8, MVT::v32i16);
2418 MVT::v32i16);
2419 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i8, MVT::v32i16);
2421 MVT::v32i16);
2422 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i1, MVT::v32i16);
2424 MVT::v32i16);
2425 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i1, MVT::v32i16);
2427 MVT::v32i16);
2428
2432
2433 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Legal);
2434 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2435
2436 SetFPMinMaxAction(MVT::v32f16);
2437 setOperationAction(ISD::LRINT, MVT::v32f16, Legal);
2438 setOperationAction(ISD::LLRINT, MVT::v8f16, Legal);
2439 }
2440
2445
2446 // Without VLX, these are widened to 512-bit compares during isel.
2447 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
2448 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
2449
2450 if (Subtarget.hasVLX()) {
2451 setGroup(MVT::v8f16);
2452 setGroup(MVT::v16f16);
2453
2464
2471
2472 // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2475
2479
2480 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2481 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2482 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2483 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2484
2485 // Need to custom widen these to prevent scalarization.
2486 setOperationAction(ISD::LOAD, MVT::v4f16, Custom);
2487 setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2488
2489 SetFPMinMaxAction(MVT::v8f16);
2490 SetFPMinMaxAction(MVT::v16f16);
2491
2492 setOperationAction(ISD::LRINT, MVT::v8f16, Legal);
2493 setOperationAction(ISD::LRINT, MVT::v16f16, Legal);
2494 }
2495 }
2496
2497 if (!Subtarget.useSoftFloat() &&
2498 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2499 addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2500 : &X86::VR128RegClass);
2501 addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2502 : &X86::VR256RegClass);
2503 // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2504 // provide the method to promote BUILD_VECTOR. Set the operation action
2505 // Custom to do the customization later.
2507 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2508 setF16Action(VT, Expand);
2509 if (!Subtarget.hasBF16())
2516 }
2517 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
2520 setOperationPromotedToType(Opc, MVT::v8bf16, MVT::v8f32);
2521 setOperationPromotedToType(Opc, MVT::v16bf16, MVT::v16f32);
2522 }
2523 setOperationAction(ISD::SETCC, MVT::v8bf16, Custom);
2524 setOperationAction(ISD::SETCC, MVT::v16bf16, Custom);
2526 addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2527 }
2528
2529 if (!Subtarget.useSoftFloat() && Subtarget.hasBF16() &&
2530 Subtarget.useAVX512Regs()) {
2531 addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2532 setF16Action(MVT::v32bf16, Expand);
2533 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
2536 setOperationPromotedToType(Opc, MVT::v32bf16, MVT::v32f32);
2537 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2539 setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2543 }
2544
2545 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX10_2()) {
2546 for (MVT VT : {MVT::v8i8, MVT::v16i8, MVT::v32i8}) {
2549 }
2554 for (MVT VT : {MVT::i32, MVT::i64, MVT::v4i32, MVT::v8i32, MVT::v16i32,
2555 MVT::v2i64, MVT::v4i64}) {
2556 if (VT == MVT::i64 && !Subtarget.is64Bit())
2557 continue;
2560 }
2561
2562 // Lower scalar bf16 arithmetic by widening to a vector op and extracting
2563 // the low element.
2564 setOperationAction(ISD::FADD, MVT::bf16, Custom);
2565 setOperationAction(ISD::FSUB, MVT::bf16, Custom);
2566 setOperationAction(ISD::FMUL, MVT::bf16, Custom);
2567 setOperationAction(ISD::FDIV, MVT::bf16, Custom);
2569 setOperationAction(ISD::FMA, MVT::bf16, Custom);
2570
2572
2573 if (Subtarget.useAVX512Regs()) {
2574 setOperationAction(ISD::FADD, MVT::v32bf16, Legal);
2575 setOperationAction(ISD::FSUB, MVT::v32bf16, Legal);
2576 setOperationAction(ISD::FMUL, MVT::v32bf16, Legal);
2577 setOperationAction(ISD::FDIV, MVT::v32bf16, Legal);
2578 setOperationAction(ISD::FSQRT, MVT::v32bf16, Legal);
2579 setOperationAction(ISD::FMA, MVT::v32bf16, Legal);
2580 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2581 SetFPMinMaxAction(MVT::v32bf16);
2582
2584 }
2585
2586 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2595 SetFPMinMaxAction(VT);
2596 }
2597 for (auto VT : {MVT::f16, MVT::f32, MVT::f64}) {
2600 }
2601 }
2602
2603 // Partial reductions that map onto the dot product instructions:
2604 // vpdpbusd / vpdpwssd (AVX512-VNNI, AVX-VNNI)
2605 // vpdpbssd / vpdpbuud (AVX-VNNI-INT8, AVX10.2)
2606 // vpdpwsud / vpdpwuud (AVX-VNNI-INT16, AVX10.2)
2607 // vdpbf16ps (AVX512-BF16)
2608 // vdpphps (AVX10.2)
2609 // 512-bit shapes are split in two when only the VEX encoding is available.
2610 if (!Subtarget.useSoftFloat()) {
2611 bool HasVNNI = Subtarget.hasVNNI() || Subtarget.hasAVXVNNI();
2612 bool HasVNNIINT8 = Subtarget.hasAVXVNNIINT8() || Subtarget.hasAVX10_2();
2613 bool HasVNNIINT16 = Subtarget.hasAVXVNNIINT16() || Subtarget.hasAVX10_2();
2614 for (MVT AccVT : {MVT::v4i32, MVT::v8i32, MVT::v16i32}) {
2615 if (AccVT == MVT::v16i32 && !Subtarget.useAVX512Regs())
2616 break;
2617 unsigned NumElts = AccVT.getVectorNumElements();
2618 MVT I8VT = MVT::getVectorVT(MVT::i8, NumElts * 4);
2619 MVT I16VT = MVT::getVectorVT(MVT::i16, NumElts * 2);
2620 MVT F32VT = MVT::getVectorVT(MVT::f32, NumElts);
2621 if (HasVNNI) {
2623 Custom);
2625 Custom);
2626 }
2627 if (HasVNNIINT8)
2630 Custom);
2631 if (HasVNNIINT16)
2634 Custom);
2635 if (Subtarget.hasBF16())
2637 MVT::getVectorVT(MVT::bf16, NumElts * 2),
2638 Custom);
2639 if (Subtarget.hasAVX10_2())
2641 MVT::getVectorVT(MVT::f16, NumElts * 2),
2642 Custom);
2643 }
2644 }
2645
2646 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2647 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
2648 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2649 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2650 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
2651 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2652
2653 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
2654 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2655 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2656 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
2657 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2658
2659 if (Subtarget.hasBWI()) {
2660 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
2661 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
2662 }
2663
2664 if (Subtarget.hasFP16()) {
2665 // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2674 // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2683 // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2688 // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2693 }
2694 }
2695
2696 if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2697 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2698 }
2699
2700 // We want to custom lower some of our intrinsics.
2704 if (!Subtarget.is64Bit()) {
2706 }
2707
2708 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2709 // handle type legalization for these operations here.
2710 //
2711 // FIXME: We really should do custom legalization for addition and
2712 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
2713 // than generic legalization for 64-bit multiplication-with-overflow, though.
2714 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2715 if (VT == MVT::i64 && !Subtarget.is64Bit())
2716 continue;
2717 // Add/Sub/Mul with overflow operations are custom lowered.
2724
2725 // Support carry in as value rather than glue.
2731 }
2732
2733 // Combine sin / cos into _sincos_stret if it is available.
2736
2737 if (Subtarget.isTargetWin64()) {
2738 setOperationAction(ISD::SDIV, MVT::i128, Custom);
2739 setOperationAction(ISD::UDIV, MVT::i128, Custom);
2740 setOperationAction(ISD::SREM, MVT::i128, Custom);
2741 setOperationAction(ISD::UREM, MVT::i128, Custom);
2750 }
2751
2752 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2753 // is. We should promote the value to 64-bits to solve this.
2754 // This is what the CRT headers do - `fmodf` is an inline header
2755 // function casting to f64 and calling `fmod`.
2756 if (Subtarget.is32Bit() &&
2757 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2758 // clang-format off
2759 for (ISD::NodeType Op :
2777 // TODO: Add ISD:::STRICT_FMODF too once implemented.
2778 ISD::FMODF})
2779 if (isOperationExpandOrLibCall(Op, MVT::f32))
2780 setOperationAction(Op, MVT::f32, Promote);
2781 // clang-format on
2782
2783 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
2784 // it, but it's just a wrapper around ldexp.
2785 if (Subtarget.isOSWindows()) {
2787 if (isOperationExpand(Op, MVT::f32))
2788 setOperationAction(Op, MVT::f32, Promote);
2789 }
2790
2791 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f16, MVT::i16);
2792 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f32, MVT::i32);
2793 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f64, MVT::i64);
2794
2795 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f16, MVT::i16);
2796 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f32, MVT::i32);
2797 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f64, MVT::i64);
2798
2799 // We have target-specific dag combine patterns for the following nodes:
2810 ISD::SHL,
2811 ISD::SRA,
2812 ISD::SRL,
2813 ISD::OR,
2814 ISD::AND,
2820 ISD::ADD,
2823 ISD::FADD,
2824 ISD::FSUB,
2825 ISD::FNEG,
2826 ISD::FMA,
2832 ISD::SUB,
2834 ISD::LOAD,
2835 ISD::LRINT,
2837 ISD::MLOAD,
2838 ISD::STORE,
2859 ISD::SETCC,
2860 ISD::MUL,
2861 ISD::UDIV,
2862 ISD::SDIV,
2863 ISD::UREM,
2864 ISD::SREM,
2869 ISD::XOR,
2877 ISD::ROTL,
2878 ISD::ROTR,
2879 ISD::FSHL,
2880 ISD::FSHR,
2884
2885 computeRegisterProperties(Subtarget.getRegisterInfo());
2886
2887 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2889 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2891 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2893
2894 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2895 // that needs to benchmarked and balanced with the potential use of vector
2896 // load/store types (PR33329, PR33914).
2899
2900 // Default loop alignment, which can be overridden by -align-loops.
2902
2903 // An out-of-order CPU can speculatively execute past a predictable branch,
2904 // but a conditional move could be stalled by an expensive earlier operation.
2905 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2906 EnableExtLdPromotion = true;
2908
2910
2911 // Default to having -disable-strictnode-mutation on
2912 IsStrictFPEnabled = true;
2913}
2914
2915// This has so far only been implemented for 64-bit MachO.
2917 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2918}
2919
2921 // Currently only MSVC CRTs mix the frame pointer into the stack guard value.
2922 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2923}
2924
2926 const SDLoc &DL) const {
2927 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2928 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2929 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2930 return SDValue(Node, 0);
2931}
2932
2935 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2936 !Subtarget.hasBWI())
2937 return TypeSplitVector;
2938
2939 // Since v8f16 is legal, widen anything over v4f16.
2940 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2941 VT.getVectorNumElements() <= 4 && !Subtarget.hasF16C() &&
2942 VT.getVectorElementType() == MVT::f16)
2943 return TypeSplitVector;
2944
2945 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2946 VT.getVectorElementType() != MVT::i1)
2947 return TypeWidenVector;
2948
2950}
2951
2953 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
2954 const LibcallLoweringInfo *libcallLowering) const {
2955 return X86::createFastISel(funcInfo, libInfo, libcallLowering);
2956}
2957
2958//===----------------------------------------------------------------------===//
2959// Other Lowering Hooks
2960//===----------------------------------------------------------------------===//
2961
2963 bool AssumeSingleUse, bool IgnoreAlignment) {
2964 if (!AssumeSingleUse && !Op.hasOneUse())
2965 return false;
2966 if (!ISD::isNormalLoad(Op.getNode()))
2967 return false;
2968
2969 // If this is an unaligned vector, make sure the target supports folding it.
2970 auto *Ld = cast<LoadSDNode>(Op.getNode());
2971 if (!IgnoreAlignment && !Subtarget.hasAVX() &&
2972 !Subtarget.hasSSEUnalignedMem() && Ld->getValueSizeInBits(0) == 128 &&
2973 Ld->getAlign() < Align(16))
2974 return false;
2975
2976 // TODO: If this is a non-temporal load and the target has an instruction
2977 // for it, it should not be folded. See "useNonTemporalLoad()".
2978
2979 return true;
2980}
2981
2983 const X86Subtarget &Subtarget,
2984 bool AssumeSingleUse) {
2985 assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2986 if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2987 return false;
2988
2989 // We can not replace a wide volatile load with a broadcast-from-memory,
2990 // because that would narrow the load, which isn't legal for volatiles.
2991 auto *Ld = cast<LoadSDNode>(Op.getNode());
2992 return !Ld->isVolatile() ||
2993 Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
2994}
2995
2997 if (!Op.hasOneUse())
2998 return false;
2999 // Peek through (oneuse) bitcast users
3000 SDNode *User = *Op->user_begin();
3001 while (User->getOpcode() == ISD::BITCAST) {
3002 if (!User->hasOneUse())
3003 return false;
3004 User = *User->user_begin();
3005 }
3006 return ISD::isNormalStore(User) || User->getOpcode() == ISD::ATOMIC_STORE;
3007}
3008
3010 if (Op.hasOneUse()) {
3011 unsigned Opcode = Op.getNode()->user_begin()->getOpcode();
3012 return (ISD::ZERO_EXTEND == Opcode);
3013 }
3014 return false;
3015}
3016
3017// Return true if its cheap to bitcast this to a scalar integer type on a GPR.
3019 if (peekThroughBitcasts(Op).getValueType().isScalarInteger())
3020 return true;
3022 return true;
3023 return false;
3024}
3025
3026// Return true if its cheap to bitcast this to a vector type.
3028 const X86Subtarget &Subtarget) {
3029 if (peekThroughBitcasts(Op).getValueType().isVector())
3030 return true;
3032 return true;
3033
3034 EVT VT = Op.getValueType();
3035 unsigned Opcode = Op.getOpcode();
3036 if ((VT == MVT::i128 || VT == MVT::i256 || VT == MVT::i512) &&
3037 DAG.getTargetLoweringInfo().getOperationAction(Opcode, VT) ==
3039 // Check for larger than legal scalar integer ops that might have been
3040 // custom lowered to vector instruction.
3041 switch (Opcode) {
3042 case ISD::BITREVERSE:
3043 return true;
3044 case ISD::SHL:
3045 case ISD::SRL:
3046 case ISD::SRA:
3047 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget);
3048 case ISD::AND:
3049 case ISD::OR:
3050 case ISD::XOR:
3051 case ISD::ADD:
3052 case ISD::SUB:
3053 case ISD::FSHL:
3054 case ISD::FSHR:
3055 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget) &&
3056 mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget);
3057 case ISD::SELECT:
3058 return mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget) &&
3059 mayFoldIntoVector(Op.getOperand(2), DAG, Subtarget);
3060 }
3061 }
3062 return X86::mayFoldLoad(Op, Subtarget, /*AssumeSingleUse=*/true,
3063 /*IgnoreAlignment=*/true);
3064}
3065
3066static bool isLogicOp(unsigned Opcode) {
3067 // TODO: Add support for X86ISD::FAND/FOR/FXOR/FANDN with test coverage.
3068 return ISD::isBitwiseLogicOp(Opcode) || X86ISD::ANDNP == Opcode;
3069}
3070
3071static bool isTargetShuffle(unsigned Opcode) {
3072 switch(Opcode) {
3073 default: return false;
3074 case X86ISD::BLENDI:
3075 case X86ISD::PSHUFB:
3076 case X86ISD::PSHUFD:
3077 case X86ISD::PSHUFHW:
3078 case X86ISD::PSHUFLW:
3079 case X86ISD::SHUFP:
3080 case X86ISD::INSERTPS:
3081 case X86ISD::EXTRQI:
3082 case X86ISD::INSERTQI:
3083 case X86ISD::VALIGN:
3084 case X86ISD::PALIGNR:
3085 case X86ISD::VSHLDQ:
3086 case X86ISD::VSRLDQ:
3087 case X86ISD::MOVLHPS:
3088 case X86ISD::MOVHLPS:
3089 case X86ISD::MOVSHDUP:
3090 case X86ISD::MOVSLDUP:
3091 case X86ISD::MOVDDUP:
3092 case X86ISD::MOVSS:
3093 case X86ISD::MOVSD:
3094 case X86ISD::MOVSH:
3095 case X86ISD::UNPCKL:
3096 case X86ISD::UNPCKH:
3097 case X86ISD::VBROADCAST:
3098 case X86ISD::VPERMILPI:
3099 case X86ISD::VPERMILPV:
3100 case X86ISD::VPERM2X128:
3101 case X86ISD::SHUF128:
3102 case X86ISD::VPERMIL2:
3103 case X86ISD::VPERMI:
3104 case X86ISD::VPPERM:
3105 case X86ISD::VPERMV:
3106 case X86ISD::VPERMV3:
3107 case X86ISD::VZEXT_MOVL:
3108 case X86ISD::COMPRESS:
3109 case X86ISD::EXPAND:
3110 return true;
3111 }
3112}
3113
3114static bool isTargetShuffleVariableMask(unsigned Opcode) {
3115 switch (Opcode) {
3116 default: return false;
3117 // Target Shuffles.
3118 case X86ISD::PSHUFB:
3119 case X86ISD::VPERMILPV:
3120 case X86ISD::VPERMIL2:
3121 case X86ISD::VPPERM:
3122 case X86ISD::VPERMV:
3123 case X86ISD::VPERMV3:
3124 return true;
3125 // 'Faux' Target Shuffles.
3126 case ISD::OR:
3127 case ISD::AND:
3128 case X86ISD::ANDNP:
3129 return true;
3130 }
3131}
3132
3135 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3137 int ReturnAddrIndex = FuncInfo->getRAIndex();
3138
3139 if (ReturnAddrIndex == 0) {
3140 // Set up a frame object for the return address.
3141 unsigned SlotSize = RegInfo->getSlotSize();
3142 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
3143 -(int64_t)SlotSize,
3144 false);
3145 FuncInfo->setRAIndex(ReturnAddrIndex);
3146 }
3147
3148 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3149}
3150
3152 bool HasSymbolicDisplacement) {
3153 // Offset should fit into 32 bit immediate field.
3154 if (!isInt<32>(Offset))
3155 return false;
3156
3157 // If we don't have a symbolic displacement - we don't have any extra
3158 // restrictions.
3159 if (!HasSymbolicDisplacement)
3160 return true;
3161
3162 // We can fold large offsets in the large code model because we always use
3163 // 64-bit offsets.
3164 if (CM == CodeModel::Large)
3165 return true;
3166
3167 // For kernel code model we know that all object resist in the negative half
3168 // of 32bits address space. We may not accept negative offsets, since they may
3169 // be just off and we may accept pretty large positive ones.
3170 if (CM == CodeModel::Kernel)
3171 return Offset >= 0;
3172
3173 // For other non-large code models we assume that latest small object is 16MB
3174 // before end of 31 bits boundary. We may also accept pretty large negative
3175 // constants knowing that all objects are in the positive half of address
3176 // space.
3177 return Offset < 16 * 1024 * 1024;
3178}
3179
3180/// Return true if the condition is an signed comparison operation.
3181static bool isX86CCSigned(X86::CondCode X86CC) {
3182 switch (X86CC) {
3183 default:
3184 llvm_unreachable("Invalid integer condition!");
3185 case X86::COND_E:
3186 case X86::COND_NE:
3187 case X86::COND_B:
3188 case X86::COND_A:
3189 case X86::COND_BE:
3190 case X86::COND_AE:
3191 return false;
3192 case X86::COND_G:
3193 case X86::COND_GE:
3194 case X86::COND_L:
3195 case X86::COND_LE:
3196 return true;
3197 }
3198}
3199
3201 switch (SetCCOpcode) {
3202 // clang-format off
3203 default: llvm_unreachable("Invalid integer condition!");
3204 case ISD::SETEQ: return X86::COND_E;
3205 case ISD::SETGT: return X86::COND_G;
3206 case ISD::SETGE: return X86::COND_GE;
3207 case ISD::SETLT: return X86::COND_L;
3208 case ISD::SETLE: return X86::COND_LE;
3209 case ISD::SETNE: return X86::COND_NE;
3210 case ISD::SETULT: return X86::COND_B;
3211 case ISD::SETUGT: return X86::COND_A;
3212 case ISD::SETULE: return X86::COND_BE;
3213 case ISD::SETUGE: return X86::COND_AE;
3214 // clang-format on
3215 }
3216}
3217
3218/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3219/// condition code, returning the condition code and the LHS/RHS of the
3220/// comparison to make.
3222 bool isFP, SDValue &LHS, SDValue &RHS,
3223 SelectionDAG &DAG) {
3224 if (!isFP) {
3226 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
3227 // X > -1 -> X == 0, jump !sign.
3228 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3229 return X86::COND_NS;
3230 }
3231 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
3232 // X < 0 -> X == 0, jump on sign.
3233 return X86::COND_S;
3234 }
3235 if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
3236 // X >= 0 -> X == 0, jump on !sign.
3237 return X86::COND_NS;
3238 }
3239 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
3240 // X < 1 -> X <= 0
3241 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3242 return X86::COND_LE;
3243 }
3244 }
3245
3246 return TranslateIntegerX86CC(SetCCOpcode);
3247 }
3248
3249 // First determine if it is required or is profitable to flip the operands.
3250
3251 // If LHS is a foldable load, but RHS is not, flip the condition.
3252 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3253 !ISD::isNON_EXTLoad(RHS.getNode())) {
3254 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3255 std::swap(LHS, RHS);
3256 }
3257
3258 switch (SetCCOpcode) {
3259 default: break;
3260 case ISD::SETOLT:
3261 case ISD::SETOLE:
3262 case ISD::SETUGT:
3263 case ISD::SETUGE:
3264 std::swap(LHS, RHS);
3265 break;
3266 }
3267
3268 // On a floating point condition, the flags are set as follows:
3269 // ZF PF CF op
3270 // 0 | 0 | 0 | X > Y
3271 // 0 | 0 | 1 | X < Y
3272 // 1 | 0 | 0 | X == Y
3273 // 1 | 1 | 1 | unordered
3274 switch (SetCCOpcode) {
3275 // clang-format off
3276 default: llvm_unreachable("Condcode should be pre-legalized away");
3277 case ISD::SETUEQ:
3278 case ISD::SETEQ: return X86::COND_E;
3279 case ISD::SETOLT: // flipped
3280 case ISD::SETOGT:
3281 case ISD::SETGT: return X86::COND_A;
3282 case ISD::SETOLE: // flipped
3283 case ISD::SETOGE:
3284 case ISD::SETGE: return X86::COND_AE;
3285 case ISD::SETUGT: // flipped
3286 case ISD::SETULT:
3287 case ISD::SETLT: return X86::COND_B;
3288 case ISD::SETUGE: // flipped
3289 case ISD::SETULE:
3290 case ISD::SETLE: return X86::COND_BE;
3291 case ISD::SETONE:
3292 case ISD::SETNE: return X86::COND_NE;
3293 case ISD::SETUO: return X86::COND_P;
3294 case ISD::SETO: return X86::COND_NP;
3295 case ISD::SETOEQ:
3296 case ISD::SETUNE: return X86::COND_INVALID;
3297 // clang-format on
3298 }
3299}
3300
3301/// Is there a floating point cmov for the specific X86 condition code?
3302/// Current x86 isa includes the following FP cmov instructions:
3303/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3304static bool hasFPCMov(unsigned X86CC) {
3305 switch (X86CC) {
3306 default:
3307 return false;
3308 case X86::COND_B:
3309 case X86::COND_BE:
3310 case X86::COND_E:
3311 case X86::COND_P:
3312 case X86::COND_A:
3313 case X86::COND_AE:
3314 case X86::COND_NE:
3315 case X86::COND_NP:
3316 return true;
3317 }
3318}
3319
3320static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
3321 return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
3322 VT.is512BitVector();
3323}
3324
3327 MachineFunction &MF, unsigned Intrinsic) const {
3328 IntrinsicInfo Info;
3330 Info.offset = 0;
3331
3333 if (!IntrData) {
3334 switch (Intrinsic) {
3335 case Intrinsic::x86_aesenc128kl:
3336 case Intrinsic::x86_aesdec128kl:
3337 Info.opc = ISD::INTRINSIC_W_CHAIN;
3338 Info.ptrVal = I.getArgOperand(1);
3339 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3340 Info.align = Align(1);
3341 Info.flags |= MachineMemOperand::MOLoad;
3342 Infos.push_back(Info);
3343 return;
3344 case Intrinsic::x86_aesenc256kl:
3345 case Intrinsic::x86_aesdec256kl:
3346 Info.opc = ISD::INTRINSIC_W_CHAIN;
3347 Info.ptrVal = I.getArgOperand(1);
3348 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3349 Info.align = Align(1);
3350 Info.flags |= MachineMemOperand::MOLoad;
3351 Infos.push_back(Info);
3352 return;
3353 case Intrinsic::x86_aesencwide128kl:
3354 case Intrinsic::x86_aesdecwide128kl:
3355 Info.opc = ISD::INTRINSIC_W_CHAIN;
3356 Info.ptrVal = I.getArgOperand(0);
3357 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3358 Info.align = Align(1);
3359 Info.flags |= MachineMemOperand::MOLoad;
3360 Infos.push_back(Info);
3361 return;
3362 case Intrinsic::x86_aesencwide256kl:
3363 case Intrinsic::x86_aesdecwide256kl:
3364 Info.opc = ISD::INTRINSIC_W_CHAIN;
3365 Info.ptrVal = I.getArgOperand(0);
3366 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3367 Info.align = Align(1);
3368 Info.flags |= MachineMemOperand::MOLoad;
3369 Infos.push_back(Info);
3370 return;
3371 case Intrinsic::x86_cmpccxadd32:
3372 case Intrinsic::x86_cmpccxadd64:
3373 case Intrinsic::x86_atomic_bts:
3374 case Intrinsic::x86_atomic_btc:
3375 case Intrinsic::x86_atomic_btr: {
3376 Info.opc = ISD::INTRINSIC_W_CHAIN;
3377 Info.ptrVal = I.getArgOperand(0);
3378 unsigned Size = I.getType()->getScalarSizeInBits();
3379 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3380 Info.align = Align(Size);
3383 Infos.push_back(Info);
3384 return;
3385 }
3386 case Intrinsic::x86_atomic_bts_rm:
3387 case Intrinsic::x86_atomic_btc_rm:
3388 case Intrinsic::x86_atomic_btr_rm: {
3389 Info.opc = ISD::INTRINSIC_W_CHAIN;
3390 Info.ptrVal = I.getArgOperand(0);
3391 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3392 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3393 Info.align = Align(Size);
3396 Infos.push_back(Info);
3397 return;
3398 }
3399 case Intrinsic::x86_aadd32:
3400 case Intrinsic::x86_aadd64:
3401 case Intrinsic::x86_aand32:
3402 case Intrinsic::x86_aand64:
3403 case Intrinsic::x86_aor32:
3404 case Intrinsic::x86_aor64:
3405 case Intrinsic::x86_axor32:
3406 case Intrinsic::x86_axor64:
3407 case Intrinsic::x86_atomic_add_cc:
3408 case Intrinsic::x86_atomic_sub_cc:
3409 case Intrinsic::x86_atomic_or_cc:
3410 case Intrinsic::x86_atomic_and_cc:
3411 case Intrinsic::x86_atomic_xor_cc: {
3412 Info.opc = ISD::INTRINSIC_W_CHAIN;
3413 Info.ptrVal = I.getArgOperand(0);
3414 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3415 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3416 Info.align = Align(Size);
3419 Infos.push_back(Info);
3420 return;
3421 }
3422 }
3423 return;
3424 }
3425
3426 switch (IntrData->Type) {
3429 case TRUNCATE_TO_MEM_VI32: {
3430 Info.opc = ISD::INTRINSIC_VOID;
3431 Info.ptrVal = I.getArgOperand(0);
3432 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
3434 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
3435 ScalarVT = MVT::i8;
3436 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
3437 ScalarVT = MVT::i16;
3438 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
3439 ScalarVT = MVT::i32;
3440
3441 Info.memVT = VT.changeElementType(ScalarVT);
3442 Info.align = Align(1);
3443 Info.flags |= MachineMemOperand::MOStore;
3444 Infos.push_back(Info);
3445 return;
3446 }
3447 case GATHER:
3448 case GATHER_AVX2: {
3449 Info.opc = ISD::INTRINSIC_W_CHAIN;
3450 Info.ptrVal = nullptr;
3451 MVT DataVT = MVT::getVT(I.getType());
3452 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3453 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3454 IndexVT.getVectorNumElements());
3455 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3456 Info.align = Align(1);
3457 Info.flags |= MachineMemOperand::MOLoad;
3458 Infos.push_back(Info);
3459 return;
3460 }
3461 case SCATTER: {
3462 Info.opc = ISD::INTRINSIC_VOID;
3463 Info.ptrVal = nullptr;
3464 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
3465 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3466 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3467 IndexVT.getVectorNumElements());
3468 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3469 Info.align = Align(1);
3470 Info.flags |= MachineMemOperand::MOStore;
3471 Infos.push_back(Info);
3472 return;
3473 }
3474 default:
3475 return;
3476 }
3477}
3478
3479/// Returns true if the target can instruction select the
3480/// specified FP immediate natively. If false, the legalizer will
3481/// materialize the FP immediate as a load from a constant pool.
3483 bool ForCodeSize) const {
3484 for (const APFloat &FPImm : LegalFPImmediates)
3485 if (Imm.bitwiseIsEqual(FPImm))
3486 return true;
3487 return false;
3488}
3489
3491 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
3492 std::optional<unsigned> ByteOffset) const {
3493 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3494
3495 auto PeekThroughOneUserBitcasts = [](const SDNode *N) {
3496 while (N->getOpcode() == ISD::BITCAST && N->hasOneUse())
3497 N = *N->user_begin();
3498 return N;
3499 };
3500
3501 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3502 // relocation target a movq or addq instruction: don't let the load shrink.
3503 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3504 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3505 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3506 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3507
3508 // If this is a (1) 128-bit or wider vector load, and any use will be used by
3509 // a legal full width instruction, then the load can typically be memory
3510 // folded into that instruction, so it's probably not worth splitting the
3511 // load. Additionally, for (2) AVX vector loads with (3) multiple uses where
3512 // (4) all of those uses are extracted directly into a store, the extract +
3513 // store can be store-folded, so it's again not worth splitting.
3514 EVT VT = Load->getValueType(0);
3515 if (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) {
3516 bool FullWidthUse = false;
3517 // The extract + store folding only helps the AVX split case, which requires
3518 // multiple uses of the load.
3519 bool AllExtractStores = (VT.is256BitVector() || VT.is512BitVector()) &&
3520 !SDValue(Load, 0).hasOneUse();
3521 for (SDUse &Use : Load->uses()) {
3522 // Skip uses of the chain value. Result 0 of the node is the load value.
3523 if (Use.getResNo() != 0)
3524 continue;
3525
3526 const SDNode *User = PeekThroughOneUserBitcasts(Use.getUser());
3527
3528 // If this use is an extract + store, it's probably not worth splitting.
3529 if (AllExtractStores && User->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
3530 all_of(User->uses(), [&](const SDUse &U) {
3531 const SDNode *Inner = PeekThroughOneUserBitcasts(U.getUser());
3532 return Inner->getOpcode() == ISD::STORE;
3533 }))
3534 continue;
3535
3536 AllExtractStores = false;
3537
3538 // If any use is a full width legal/target bin op, then assume its legal
3539 // and won't split.
3540 if (isBinOp(User->getOpcode()) &&
3541 (isOperationLegal(User->getOpcode(), User->getValueType(0)) ||
3542 User->getOpcode() > ISD::BUILTIN_OP_END))
3543 FullWidthUse = true;
3544 }
3545
3546 if (AllExtractStores)
3547 return false;
3548
3549 // If we have an user that uses the full vector width, then this use is
3550 // only worth splitting if the offset isn't 0 (to avoid an
3551 // EXTRACT_SUBVECTOR) or we're loading a scalar integer.
3552 if (FullWidthUse)
3553 return (ByteOffset.value_or(0) > 0) || NewVT.isScalarInteger();
3554 }
3555
3556 return true;
3557}
3558
3559/// Returns true if it is beneficial to convert a load of a constant
3560/// to just the constant itself.
3562 Type *Ty) const {
3563 assert(Ty->isIntegerTy());
3564
3565 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3566 if (BitSize == 0 || BitSize > 64)
3567 return false;
3568 return true;
3569}
3570
3572 // If we are using XMM registers in the ABI and the condition of the select is
3573 // a floating-point compare and we have blendv or conditional move, then it is
3574 // cheaper to select instead of doing a cross-register move and creating a
3575 // load that depends on the compare result.
3576 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3577 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3578}
3579
3581 // TODO: It might be a win to ease or lift this restriction, but the generic
3582 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3583 if (VT.isVector() && Subtarget.hasAVX512())
3584 return false;
3585
3586 return true;
3587}
3588
3590 EVT) const {
3591 // With CCMP, keep and/or(setcc, setcc) trees intact so LowerSELECT can
3592 // emit them as CCMP chains rather than splitting into chained selects.
3593 return !(Subtarget.hasCCMP() && VT.isScalarInteger());
3594}
3595
3597 SDValue C) const {
3598 // TODO: We handle scalars using custom code, but generic combining could make
3599 // that unnecessary.
3600 APInt MulC;
3601 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3602 return false;
3603
3604 if (VT.isVector() && VT.getScalarSizeInBits() == 8) {
3605 // Check whether a vXi8 multiply can be decomposed into two shifts
3606 // (decomposing 2^m ± 2^n as 2^(a+b) ± 2^b). Similar to
3607 // DAGCombiner::visitMUL, consider the constant `2` decomposable as
3608 // (2^0 + 1).
3609 APInt ShiftedMulC = MulC.abs();
3610 unsigned TZeros = ShiftedMulC == 2 ? 0 : ShiftedMulC.countr_zero();
3611 ShiftedMulC.lshrInPlace(TZeros);
3612 if ((ShiftedMulC - 1).isPowerOf2() || (ShiftedMulC + 1).isPowerOf2())
3613 return true;
3614 }
3615
3616 // Find the type this will be legalized too. Otherwise we might prematurely
3617 // convert this to shl+add/sub and then still have to type legalize those ops.
3618 // Another choice would be to defer the decision for illegal types until
3619 // after type legalization. But constant splat vectors of i64 can't make it
3620 // through type legalization on 32-bit targets so we would need to special
3621 // case vXi64.
3622 while (getTypeAction(Context, VT) != TypeLegal)
3623 VT = getTypeToTransformTo(Context, VT);
3624
3625 // If vector multiply is legal, assume that's faster than shl + add/sub.
3626 // Multiply is a complex op with higher latency and lower throughput in
3627 // most implementations, sub-vXi32 vector multiplies are always fast,
3628 // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3629 // is always going to be slow.
3630 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3631 if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3632 (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3633 return false;
3634
3635 // shl+add, shl+sub, shl+add+neg
3636 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3637 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3638}
3639
3642 unsigned Index) const {
3645
3646 // Mask vectors support all subregister combinations and operations that
3647 // extract half of vector.
3648 if (ResVT.getVectorElementType() == MVT::i1) {
3649 if (Index == 0 || ((ResVT.getSizeInBits() * 2 == SrcVT.getSizeInBits()) &&
3650 (Index == ResVT.getVectorNumElements())))
3653 }
3654
3655 if (Index == 0)
3657 else if ((Index % ResVT.getVectorNumElements()) == 0)
3660}
3661
3663 unsigned Opc = VecOp.getOpcode();
3664
3665 // Assume target opcodes can't be scalarized.
3666 // TODO - do we have any exceptions?
3667 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
3668 return false;
3669
3670 // If the vector op is not supported, try to convert to scalar.
3671 EVT VecVT = VecOp.getValueType();
3673 return true;
3674
3675 // If the vector op is supported, but the scalar op is not, the transform may
3676 // not be worthwhile.
3677 EVT ScalarVT = VecVT.getScalarType();
3678 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3679}
3680
3682 bool) const {
3683 // TODO: Allow vectors?
3684 if (VT.isVector())
3685 return false;
3686 return VT.isSimple() || !isOperationExpand(Opcode, VT);
3687}
3688
3690 // Speculate cttz only if we can directly use TZCNT/CMOV, can promote to
3691 // i32/i64 or can rely on BSF passthrough value.
3692 return Subtarget.hasBMI() || Subtarget.canUseCMOV() ||
3693 Subtarget.hasBitScanPassThrough() ||
3694 (!Ty->isVectorTy() &&
3695 Ty->getScalarSizeInBits() < (Subtarget.is64Bit() ? 64u : 32u));
3696}
3697
3699 // Speculate ctlz only if we can directly use LZCNT/CMOV, or can rely on BSR
3700 // passthrough value.
3701 return Subtarget.hasLZCNT() || Subtarget.canUseCMOV() ||
3702 Subtarget.hasBitScanPassThrough();
3703}
3704
3706 // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3707 // expensive than a straight movsd. On the other hand, it's important to
3708 // shrink long double fp constant since fldt is very slow.
3709 return !Subtarget.hasSSE2() || VT == MVT::f80;
3710}
3711
3713 return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3714 (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3715}
3716
3718 const SelectionDAG &DAG,
3719 const MachineMemOperand &MMO) const {
3720 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3721 BitcastVT.getVectorElementType() == MVT::i1)
3722 return false;
3723
3724 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3725 return false;
3726
3727 if (LoadVT.isVector() && BitcastVT.isVector()) {
3728 // If both types are legal vectors, it's always ok to convert them.
3729 // Don't convert to an illegal type.
3730 if (isTypeLegal(LoadVT))
3731 return isTypeLegal(BitcastVT);
3732 }
3733
3734 // If we have a large vector type (even if illegal), don't bitcast to large
3735 // (illegal) scalar types. Better to load fewer vectors and extract.
3736 if (LoadVT.isVector() && !BitcastVT.isVector() && LoadVT.isInteger() &&
3737 BitcastVT.isInteger() && (LoadVT.getSizeInBits() % 128) == 0)
3738 return false;
3739
3740 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3741}
3742
3744 const MachineFunction &MF) const {
3745 // Do not merge to float value size (128 bytes) if no implicit
3746 // float attribute is set.
3747 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3748
3749 if (NoFloat) {
3750 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3751 return (MemVT.getSizeInBits() <= MaxIntSize);
3752 }
3753 // Make sure we don't merge greater than our preferred vector
3754 // width.
3755 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3756 return false;
3757
3758 return true;
3759}
3760
3762 return Subtarget.hasFastLZCNT();
3763}
3764
3766
3768 const Instruction &AndI) const {
3769 return true;
3770}
3771
3773 // Scalar integer and-not compares are efficiently handled by NOT+TEST (or
3774 // BMI ANDN).
3775 return Y.getValueType().isScalarInteger();
3776}
3777
3779 EVT VT = Y.getValueType();
3780
3781 if (!VT.isVector()) {
3782 if (!Subtarget.hasBMI())
3783 return false;
3784
3785 // There are only 32-bit and 64-bit forms for 'andn'.
3786 if (VT != MVT::i32 && VT != MVT::i64)
3787 return false;
3788 return !isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque();
3789 }
3790
3791 // Vector.
3792 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3793 return false;
3794
3795 if (VT == MVT::v4i32)
3796 return true;
3797
3798 return Subtarget.hasSSE2();
3799}
3800
3802 return X.getValueType().isScalarInteger(); // 'bt'
3803}
3804
3808 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3809 SelectionDAG &DAG) const {
3810 // Does baseline recommend not to perform the fold by default?
3812 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3813 return false;
3814 // For scalars this transform is always beneficial.
3815 if (X.getValueType().isScalarInteger())
3816 return true;
3817 // If all the shift amounts are identical, then transform is beneficial even
3818 // with rudimentary SSE2 shifts.
3819 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3820 return true;
3821 // If we have AVX2 with it's powerful shift operations, then it's also good.
3822 if (Subtarget.hasAVX2())
3823 return true;
3824 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3825 return NewShiftOpcode == ISD::SHL;
3826}
3827
3829 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3830 const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3831 if (!VT.isInteger())
3832 return ShiftOpc;
3833
3834 bool PreferRotate = false;
3835 if (VT.isVector()) {
3836 // For vectors, if we have rotate instruction support, then its definetly
3837 // best. Otherwise its not clear what the best so just don't make changed.
3838 PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3839 VT.getScalarType() == MVT::i64);
3840 } else if (isTypeLegal(VT)) {
3841 // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3842 // rotate unless we have a zext mask+shr. Rotates on illegal types are
3843 // expanded to shifts, so never prefer them there.
3844 PreferRotate = Subtarget.hasBMI2();
3845 if (!PreferRotate) {
3846 unsigned MaskBits =
3847 VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3848 PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3849 }
3850 }
3851
3852 if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3853 assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3854
3855 if (PreferRotate && MayTransformRotate)
3856 return ISD::ROTL;
3857
3858 // If vector we don't really get much benefit swapping around constants.
3859 // Maybe we could check if the DAG has the flipped node already in the
3860 // future.
3861 if (VT.isVector())
3862 return ShiftOpc;
3863
3864 // See if the beneficial to swap shift type.
3865 if (ShiftOpc == ISD::SHL) {
3866 // If the current setup has imm64 mask, then inverse will have
3867 // at least imm32 mask (or be zext i32 -> i64).
3868 if (VT == MVT::i64)
3869 return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3870 : ShiftOpc;
3871
3872 // We can only benefit if req at least 7-bit for the mask. We
3873 // don't want to replace shl of 1,2,3 as they can be implemented
3874 // with lea/add.
3875 return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3876 }
3877
3878 if (VT == MVT::i64)
3879 // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3880 // extremely efficient.
3881 return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3882
3883 // Keep small shifts as shl so we can generate add/lea.
3884 return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3885 }
3886
3887 // We prefer rotate for vectors of if we won't get a zext mask with SRL
3888 // (PreferRotate will be set in the latter case).
3889 if (PreferRotate || !MayTransformRotate || VT.isVector())
3890 return ShiftOpc;
3891
3892 // Non-vector type and we have a zext mask with SRL.
3893 return ISD::SRL;
3894}
3895
3897 // Prefer inc-of-add for scalars and single-element vectors, and sub-of-not
3898 // for multi-element vectors.
3899 return VT.isScalarInteger() ||
3900 (VT.isVector() && VT.getVectorElementCount().isScalar());
3901}
3902
3905 const Value *Lhs,
3906 const Value *Rhs,
3907 const Function *) const {
3908 using namespace llvm::PatternMatch;
3909 const X86Options &CLOpts = Subtarget.getCLOpts();
3910 int BaseCost = CLOpts.br_merging_base_cost;
3911 // With CCMP, branches can be merged in a more efficient way.
3912 if (BaseCost >= 0 && Subtarget.hasCCMP())
3913 BaseCost += CLOpts.br_merging_ccmp_bias;
3914 // a == b && a == c is a fast pattern on x86.
3915 if (BaseCost >= 0 && Opc == Instruction::And &&
3918 BaseCost += 1;
3919
3920 // For OR conditions with EQ comparisons, prefer splitting into branches
3921 // (unless CCMP is available). OR+EQ cannot be optimized via bitwise ops,
3922 // unlike OR+NE which becomes (P|Q)!=0. Similarly, don't split signed
3923 // comparisons (SLT, SGT) that can be optimized.
3924 if (BaseCost >= 0 && !Subtarget.hasCCMP() && Opc == Instruction::Or &&
3927 return {-1, -1, -1};
3928
3929 return {BaseCost, CLOpts.br_merging_likely_bias,
3930 CLOpts.br_merging_unlikely_bias};
3931}
3932
3934 return N->getOpcode() != ISD::FP_EXTEND;
3935}
3936
3938 const SDNode *N) const {
3939 assert(((N->getOpcode() == ISD::SHL &&
3940 N->getOperand(0).getOpcode() == ISD::SRL) ||
3941 (N->getOpcode() == ISD::SRL &&
3942 N->getOperand(0).getOpcode() == ISD::SHL)) &&
3943 "Expected shift-shift mask");
3944 // TODO: Should we always create i64 masks? Or only folded immediates?
3945 EVT VT = N->getValueType(0);
3946 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3947 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3948 // Only fold if the shift values are equal - so it folds to AND.
3949 // TODO - we should fold if either is a non-uniform vector but we don't do
3950 // the fold for non-splats yet.
3951 return N->getOperand(1) == N->getOperand(0).getOperand(1);
3952 }
3954}
3955
3957 EVT VT = Y.getValueType();
3958
3959 // For vectors, we don't have a preference, but we probably want a mask.
3960 if (VT.isVector())
3961 return false;
3962
3963 unsigned MaxWidth = Subtarget.is64Bit() ? 64 : 32;
3964 return VT.getScalarSizeInBits() <= MaxWidth;
3965}
3966
3969 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3971 !Subtarget.isOSWindows())
3974 ExpansionFactor);
3975}
3976
3978 // Any legal vector type can be splatted more efficiently than
3979 // loading/spilling from memory.
3980 return isTypeLegal(VT);
3981}
3982
3984 MVT VT = MVT::getIntegerVT(NumBits);
3985 if (isTypeLegal(VT))
3986 return VT;
3987
3988 // PMOVMSKB can handle this.
3989 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
3990 return MVT::v16i8;
3991
3992 // VPMOVMSKB can handle this.
3993 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
3994 return MVT::v32i8;
3995
3996 // TODO: Allow 64-bit type for 32-bit target.
3997 // TODO: 512-bit types should be allowed, but make sure that those
3998 // cases are handled in combineVectorSizedSetCCEquality().
3999
4001}
4002
4003/// Val is the undef sentinel value or equal to the specified value.
4004static bool isUndefOrEqual(int Val, int CmpVal) {
4005 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
4006}
4007
4008/// Return true if every element in Mask is the undef sentinel value or equal to
4009/// the specified value.
4010static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
4011 return llvm::all_of(Mask, [CmpVal](int M) {
4012 return (M == SM_SentinelUndef) || (M == CmpVal);
4013 });
4014}
4015
4016/// Return true if every element in Mask, beginning from position Pos and ending
4017/// in Pos+Size is the undef sentinel value or equal to the specified value.
4018static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
4019 unsigned Size) {
4020 return llvm::all_of(Mask.slice(Pos, Size),
4021 [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
4022}
4023
4024/// Val is either the undef or zero sentinel value.
4025static bool isUndefOrZero(int Val) {
4026 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
4027}
4028
4029/// Return true if every element in Mask, beginning from position Pos and ending
4030/// in Pos+Size is the undef sentinel value.
4031static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4032 return llvm::all_of(Mask.slice(Pos, Size), equal_to(SM_SentinelUndef));
4033}
4034
4035/// Return true if the mask creates a vector whose lower half is undefined.
4037 unsigned NumElts = Mask.size();
4038 return isUndefInRange(Mask, 0, NumElts / 2);
4039}
4040
4041/// Return true if the mask creates a vector whose upper half is undefined.
4043 unsigned NumElts = Mask.size();
4044 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
4045}
4046
4047/// Return true if Val falls within the specified range (L, H].
4048static bool isInRange(int Val, int Low, int Hi) {
4049 return (Val >= Low && Val < Hi);
4050}
4051
4052/// Return true if the value of any element in Mask falls within the specified
4053/// range (L, H].
4054static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
4055 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
4056}
4057
4058/// Return true if the value of any element in Mask is the zero sentinel value.
4059static bool isAnyZero(ArrayRef<int> Mask) {
4060 return llvm::any_of(Mask, equal_to(SM_SentinelZero));
4061}
4062
4063/// Return true if Val is undef or if its value falls within the
4064/// specified range (L, H].
4065static bool isUndefOrInRange(int Val, int Low, int Hi) {
4066 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
4067}
4068
4069/// Return true if every element in Mask is undef or if its value
4070/// falls within the specified range (L, H].
4071static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4072 return llvm::all_of(
4073 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
4074}
4075
4076/// Return true if Val is undef, zero or if its value falls within the
4077/// specified range (L, H].
4078static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4079 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
4080}
4081
4082/// Return true if every element in Mask is undef, zero or if its value
4083/// falls within the specified range (L, H].
4084static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4085 return llvm::all_of(
4086 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
4087}
4088
4089/// Return true if every element in Mask, is an in-place blend/select mask or is
4090/// undef.
4091[[maybe_unused]] static bool isBlendOrUndef(ArrayRef<int> Mask) {
4092 unsigned NumElts = Mask.size();
4093 for (auto [I, M] : enumerate(Mask))
4094 if (!isUndefOrEqual(M, I) && !isUndefOrEqual(M, I + NumElts))
4095 return false;
4096 return true;
4097}
4098
4099/// Return true if every element in Mask, beginning
4100/// from position Pos and ending in Pos + Size, falls within the specified
4101/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
4102static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
4103 unsigned Size, int Low, int Step = 1) {
4104 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4105 if (!isUndefOrEqual(Mask[i], Low))
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/// sequential range (Low, Low+Size], or is undef or is zero.
4114 unsigned Size, int Low,
4115 int Step = 1) {
4116 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4117 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4118 return false;
4119 return true;
4120}
4121
4122/// Return true if every element in Mask, beginning
4123/// from position Pos and ending in Pos+Size is undef or is zero.
4124static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4125 unsigned Size) {
4126 return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
4127}
4128
4129/// Return true if every element of a single input is referenced by the shuffle
4130/// mask. i.e. it just permutes them all.
4132 unsigned NumElts = Mask.size();
4133 APInt DemandedElts = APInt::getZero(NumElts);
4134 for (int M : Mask)
4135 if (isInRange(M, 0, NumElts))
4136 DemandedElts.setBit(M);
4137 return DemandedElts.isAllOnes();
4138}
4139
4140/// Helper function to test whether a shuffle mask could be
4141/// simplified by widening the elements being shuffled.
4142///
4143/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4144/// leaves it in an unspecified state.
4145///
4146/// NOTE: This must handle normal vector shuffle masks and *target* vector
4147/// shuffle masks. The latter have the special property of a '-2' representing
4148/// a zero-ed lane of a vector.
4150 SmallVectorImpl<int> &WidenedMask) {
4151 WidenedMask.assign(Mask.size() / 2, 0);
4152 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4153 int M0 = Mask[i];
4154 int M1 = Mask[i + 1];
4155
4156 // If both elements are undef, its trivial.
4157 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4158 WidenedMask[i / 2] = SM_SentinelUndef;
4159 continue;
4160 }
4161
4162 // Check for an undef mask and a mask value properly aligned to fit with
4163 // a pair of values. If we find such a case, use the non-undef mask's value.
4164 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4165 WidenedMask[i / 2] = M1 / 2;
4166 continue;
4167 }
4168 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4169 WidenedMask[i / 2] = M0 / 2;
4170 continue;
4171 }
4172
4173 // When zeroing, we need to spread the zeroing across both lanes to widen.
4174 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4175 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4177 WidenedMask[i / 2] = SM_SentinelZero;
4178 continue;
4179 }
4180 return false;
4181 }
4182
4183 // Finally check if the two mask values are adjacent and aligned with
4184 // a pair.
4185 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4186 WidenedMask[i / 2] = M0 / 2;
4187 continue;
4188 }
4189
4190 // Otherwise we can't safely widen the elements used in this shuffle.
4191 return false;
4192 }
4193 assert(WidenedMask.size() == Mask.size() / 2 &&
4194 "Incorrect size of mask after widening the elements!");
4195
4196 return true;
4197}
4198
4200 const APInt &Zeroable,
4201 bool V2IsZero,
4202 SmallVectorImpl<int> &WidenedMask) {
4203 // Create an alternative mask with info about zeroable elements.
4204 // Here we do not set undef elements as zeroable.
4205 SmallVector<int, 64> ZeroableMask(Mask);
4206 if (V2IsZero) {
4207 assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
4208 for (int i = 0, Size = Mask.size(); i != Size; ++i)
4209 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
4210 ZeroableMask[i] = SM_SentinelZero;
4211 }
4212 return canWidenShuffleElements(ZeroableMask, WidenedMask);
4213}
4214
4216 SmallVector<int, 32> WidenedMask;
4217 return canWidenShuffleElements(Mask, WidenedMask);
4218}
4219
4220// Attempt to narrow/widen shuffle mask until it matches the target number of
4221// elements.
4222static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
4223 SmallVectorImpl<int> &ScaledMask) {
4224 unsigned NumSrcElts = Mask.size();
4225 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
4226 "Illegal shuffle scale factor");
4227
4228 // Narrowing is guaranteed to work.
4229 if (NumDstElts >= NumSrcElts) {
4230 int Scale = NumDstElts / NumSrcElts;
4231 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
4232 return true;
4233 }
4234
4235 // We have to repeat the widening until we reach the target size, but we can
4236 // split out the first widening as it sets up ScaledMask for us.
4237 if (canWidenShuffleElements(Mask, ScaledMask)) {
4238 while (ScaledMask.size() > NumDstElts) {
4239 SmallVector<int, 16> WidenedMask;
4240 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
4241 return false;
4242 ScaledMask = std::move(WidenedMask);
4243 }
4244 return true;
4245 }
4246
4247 return false;
4248}
4249
4250static bool canScaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts) {
4251 SmallVector<int, 32> ScaledMask;
4252 return scaleShuffleElements(Mask, NumDstElts, ScaledMask);
4253}
4254
4255// Helper to grow the shuffle mask for a larger value type.
4256// NOTE: This is different to scaleShuffleElements which is a same size type.
4257static void growShuffleMask(ArrayRef<int> SrcMask,
4258 SmallVectorImpl<int> &DstMask,
4259 unsigned SrcSizeInBits, unsigned DstSizeInBits) {
4260 assert(DstMask.empty() && "Expected an empty shuffle mas");
4261 assert((DstSizeInBits % SrcSizeInBits) == 0 && "Illegal shuffle scale");
4262 unsigned Scale = DstSizeInBits / SrcSizeInBits;
4263 unsigned NumSrcElts = SrcMask.size();
4264 DstMask.assign(SrcMask.begin(), SrcMask.end());
4265 for (int &M : DstMask) {
4266 if (M < 0)
4267 continue;
4268 M = (M % NumSrcElts) + ((M / NumSrcElts) * Scale * NumSrcElts);
4269 }
4270 DstMask.append((Scale - 1) * NumSrcElts, SM_SentinelUndef);
4271}
4272
4273/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4275 return isNullConstant(Elt) || isNullFPConstant(Elt);
4276}
4277
4278// Build a vector of constants.
4279// Use an UNDEF node if MaskElt == -1.
4280// Split 64-bit constants in the 32-bit mode.
4282 const SDLoc &dl, bool IsMask = false) {
4283
4285 bool Split = false;
4286
4287 MVT ConstVecVT = VT;
4288 unsigned NumElts = VT.getVectorNumElements();
4289 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4290 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4291 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4292 Split = true;
4293 }
4294
4295 MVT EltVT = ConstVecVT.getVectorElementType();
4296 for (unsigned i = 0; i < NumElts; ++i) {
4297 bool IsUndef = Values[i] < 0 && IsMask;
4298 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4299 DAG.getConstant(Values[i], dl, EltVT);
4300 Ops.push_back(OpNode);
4301 if (Split)
4302 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4303 DAG.getConstant(0, dl, EltVT));
4304 }
4305 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4306 if (Split)
4307 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4308 return ConstsNode;
4309}
4310
4311static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
4312 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4313 assert(Bits.size() == Undefs.getBitWidth() &&
4314 "Unequal constant and undef arrays");
4316 bool Split = false;
4317
4318 MVT ConstVecVT = VT;
4319 unsigned NumElts = VT.getVectorNumElements();
4320 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4321 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4322 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4323 Split = true;
4324 }
4325
4326 MVT EltVT = ConstVecVT.getVectorElementType();
4327 MVT EltIntVT = EltVT.changeTypeToInteger();
4328 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
4329 if (Undefs[i]) {
4330 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
4331 continue;
4332 }
4333 const APInt &V = Bits[i];
4334 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
4335 if (Split) {
4336 Ops.push_back(DAG.getConstant(V.extractBits(32, 0), dl, EltVT));
4337 Ops.push_back(DAG.getConstant(V.extractBits(32, 32), dl, EltVT));
4338 } else {
4339 Ops.push_back(DAG.getBitcast(EltVT, DAG.getConstant(V, dl, EltIntVT)));
4340 }
4341 }
4342
4343 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4344 return DAG.getBitcast(VT, ConstsNode);
4345}
4346
4348 SelectionDAG &DAG, const SDLoc &dl) {
4349 APInt Undefs = APInt::getZero(Bits.size());
4350 return getConstVector(Bits, Undefs, VT, DAG, dl);
4351}
4352
4353/// Returns a vector of specified type with all zero elements.
4354static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
4355 SelectionDAG &DAG, const SDLoc &dl) {
4356 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
4357 VT.getVectorElementType() == MVT::i1) &&
4358 "Unexpected vector type");
4359
4360 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4361 // type. This ensures they get CSE'd. But if the integer type is not
4362 // available, use a floating-point +0.0 instead.
4363 SDValue Vec;
4364 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4365 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4366 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4367 } else if (VT.isFloatingPoint() &&
4369 Vec = DAG.getConstantFP(+0.0, dl, VT);
4370 } else if (VT.getVectorElementType() == MVT::i1) {
4371 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
4372 "Unexpected vector type");
4373 Vec = DAG.getConstant(0, dl, VT);
4374 } else {
4375 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4376 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4377 }
4378 return DAG.getBitcast(VT, Vec);
4379}
4380
4381// Helper to determine if the ops are all the extracted subvectors come from a
4382// single source. If we allow commute they don't have to be in order (Lo/Hi).
4383static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
4384 if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4385 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4386 LHS.getValueType() != RHS.getValueType() ||
4387 LHS.getOperand(0) != RHS.getOperand(0))
4388 return SDValue();
4389
4390 SDValue Src = LHS.getOperand(0);
4391 if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
4392 return SDValue();
4393
4394 unsigned NumElts = LHS.getValueType().getVectorNumElements();
4395 if ((LHS.getConstantOperandAPInt(1) == 0 &&
4396 RHS.getConstantOperandAPInt(1) == NumElts) ||
4397 (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
4398 LHS.getConstantOperandAPInt(1) == NumElts))
4399 return Src;
4400
4401 return SDValue();
4402}
4403
4404static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4405 const SDLoc &dl, unsigned vectorWidth) {
4406 EVT VT = Vec.getValueType();
4407 EVT ElVT = VT.getVectorElementType();
4408 unsigned ResultNumElts =
4409 (VT.getVectorNumElements() * vectorWidth) / VT.getSizeInBits();
4410 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, ResultNumElts);
4411
4412 assert(ResultVT.getSizeInBits() == vectorWidth &&
4413 "Illegal subvector extraction");
4414
4415 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4416 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4417 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4418
4419 // This is the index of the first element of the vectorWidth-bit chunk
4420 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4421 IdxVal &= ~(ElemsPerChunk - 1);
4422
4423 // If the input is a buildvector just emit a smaller one.
4424 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4425 return DAG.getBuildVector(ResultVT, dl,
4426 Vec->ops().slice(IdxVal, ElemsPerChunk));
4427
4428 // Check if we're extracting the upper undef of a widening pattern.
4429 if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
4430 Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
4431 isNullConstant(Vec.getOperand(2)))
4432 return DAG.getUNDEF(ResultVT);
4433
4434 return DAG.getExtractSubvector(dl, ResultVT, Vec, IdxVal);
4435}
4436
4437/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4438/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4439/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4440/// instructions or a simple subregister reference. Idx is an index in the
4441/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4442/// lowering EXTRACT_VECTOR_ELT operations easier.
4443static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4444 SelectionDAG &DAG, const SDLoc &dl) {
4446 Vec.getValueType().is512BitVector()) &&
4447 "Unexpected vector size!");
4448 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4449}
4450
4451/// Generate a DAG to grab 256-bits from a 512-bit vector.
4452static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4453 SelectionDAG &DAG, const SDLoc &dl) {
4454 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4455 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4456}
4457
4458static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4459 SelectionDAG &DAG, const SDLoc &dl,
4460 unsigned vectorWidth) {
4461 assert((vectorWidth == 128 || vectorWidth == 256) &&
4462 "Unsupported vector width");
4463 // Inserting UNDEF is Result
4464 if (Vec.isUndef())
4465 return Result;
4466
4467 // Insert the relevant vectorWidth bits.
4468 EVT VT = Vec.getValueType();
4469 unsigned ElemsPerChunk = vectorWidth / VT.getScalarSizeInBits();
4470 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4471
4472 // This is the index of the first element of the vectorWidth-bit chunk
4473 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4474 IdxVal &= ~(ElemsPerChunk - 1);
4475 return DAG.getInsertSubvector(dl, Result, Vec, IdxVal);
4476}
4477
4478/// Generate a DAG to put 128-bits into a vector > 128 bits. This
4479/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4480/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4481/// simple superregister reference. Idx is an index in the 128 bits
4482/// we want. It need not be aligned to a 128-bit boundary. That makes
4483/// lowering INSERT_VECTOR_ELT operations easier.
4484static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4485 SelectionDAG &DAG, const SDLoc &dl) {
4486 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4487 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4488}
4489
4490/// Widen a vector to a larger size with the same scalar type, with the new
4491/// elements either zero or undef.
4492static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
4493 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4494 const SDLoc &dl) {
4495 EVT VecVT = Vec.getValueType();
4497 VecVT.getScalarType() == VT.getScalarType() &&
4498 "Unsupported vector widening type");
4499 // If the upper 128-bits of a build vector are already undef/zero, then try to
4500 // widen from the lower 128-bits.
4501 if (Vec.getOpcode() == ISD::BUILD_VECTOR && VecVT.is256BitVector()) {
4502 unsigned NumSrcElts = VecVT.getVectorNumElements();
4503 ArrayRef<SDUse> Hi = Vec->ops().drop_front(NumSrcElts / 2);
4504 if (all_of(Hi, [&](SDValue V) {
4505 return V.isUndef() || (ZeroNewElements && X86::isZeroNode(V));
4506 }))
4507 Vec = extract128BitVector(Vec, 0, DAG, dl);
4508 }
4509 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
4510 : DAG.getUNDEF(VT);
4511 return DAG.getInsertSubvector(dl, Res, Vec, 0);
4512}
4513
4514/// Widen a vector to a larger size with the same scalar type, with the new
4515/// elements either zero or undef.
4516static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
4517 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4518 const SDLoc &dl, unsigned WideSizeInBits) {
4519 assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
4520 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
4521 "Unsupported vector widening type");
4522 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
4523 MVT SVT = Vec.getSimpleValueType().getScalarType();
4524 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
4525 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4526}
4527
4528/// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
4529/// and bitcast with integer types.
4530static MVT widenMaskVectorType(MVT VT, const X86Subtarget &Subtarget) {
4531 assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
4532 unsigned NumElts = VT.getVectorNumElements();
4533 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
4534 return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4535 return VT;
4536}
4537
4538/// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
4539/// bitcast with integer types.
4540static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
4541 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4542 const SDLoc &dl) {
4543 MVT VT = widenMaskVectorType(Vec.getSimpleValueType(), Subtarget);
4544 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4545}
4546
4547// Helper function to collect subvector ops that are concatenated together,
4548// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
4549// The subvectors in Ops are guaranteed to be the same type.
4551 SelectionDAG &DAG) {
4552 assert(Ops.empty() && "Expected an empty ops vector");
4553
4554 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
4555 Ops.append(N->op_begin(), N->op_end());
4556 return true;
4557 }
4558
4559 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
4560 SDValue Src = N->getOperand(0);
4561 SDValue Sub = N->getOperand(1);
4562 const APInt &Idx = N->getConstantOperandAPInt(2);
4563 EVT VT = Src.getValueType();
4564 EVT SubVT = Sub.getValueType();
4565
4566 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
4567 // insert_subvector(undef, x, lo)
4568 if (Idx == 0 && Src.isUndef()) {
4569 Ops.push_back(Sub);
4570 Ops.push_back(DAG.getUNDEF(SubVT));
4571 return true;
4572 }
4573 if (Idx == (VT.getVectorNumElements() / 2)) {
4574 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
4575 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
4576 Src.getOperand(1).getValueType() == SubVT &&
4577 isNullConstant(Src.getOperand(2))) {
4578 // Attempt to recurse into inner (matching) concats.
4579 SDValue Lo = Src.getOperand(1);
4580 SDValue Hi = Sub;
4581 SmallVector<SDValue, 2> LoOps, HiOps;
4582 if (collectConcatOps(Lo.getNode(), LoOps, DAG) &&
4583 collectConcatOps(Hi.getNode(), HiOps, DAG) &&
4584 LoOps.size() == HiOps.size()) {
4585 Ops.append(LoOps);
4586 Ops.append(HiOps);
4587 return true;
4588 }
4589 Ops.push_back(Lo);
4590 Ops.push_back(Hi);
4591 return true;
4592 }
4593 // insert_subvector(x, extract_subvector(x, lo), hi)
4594 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4595 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
4596 Ops.append(2, Sub);
4597 return true;
4598 }
4599 // insert_subvector(undef, x, hi)
4600 if (Src.isUndef()) {
4601 Ops.push_back(DAG.getUNDEF(SubVT));
4602 Ops.push_back(Sub);
4603 return true;
4604 }
4605 }
4606 }
4607 }
4608
4609 if (N->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4610 EVT VT = N->getValueType(0);
4611 SDValue Src = N->getOperand(0);
4612 uint64_t Idx = N->getConstantOperandVal(1);
4613
4614 // Collect all the subvectors from the source vector and slice off the
4615 // extraction.
4617 if (collectConcatOps(Src.getNode(), SrcOps, DAG) &&
4618 VT.getSizeInBits() > SrcOps[0].getValueSizeInBits() &&
4619 (VT.getSizeInBits() % SrcOps[0].getValueSizeInBits()) == 0 &&
4620 (Idx % SrcOps[0].getValueType().getVectorNumElements()) == 0) {
4621 unsigned SubIdx = Idx / SrcOps[0].getValueType().getVectorNumElements();
4622 unsigned NumSubs = VT.getSizeInBits() / SrcOps[0].getValueSizeInBits();
4623 Ops.append(SrcOps.begin() + SubIdx, SrcOps.begin() + SubIdx + NumSubs);
4624 return true;
4625 }
4626 }
4627
4628 assert(Ops.empty() && "Expected an empty ops vector");
4629 return false;
4630}
4631
4632// Helper to check if \p V can be split into subvectors and the upper subvectors
4633// are all undef. In which case return the lower subvector.
4635 SelectionDAG &DAG) {
4636 SmallVector<SDValue> SubOps;
4637 if (!collectConcatOps(V.getNode(), SubOps, DAG))
4638 return SDValue();
4639
4640 unsigned NumSubOps = SubOps.size();
4641 unsigned HalfNumSubOps = NumSubOps / 2;
4642 assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
4643
4644 ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
4645 if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
4646 return SDValue();
4647
4648 EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
4649 ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
4650 return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
4651}
4652
4653// Helper to check if we can access all the constituent subvectors without any
4654// extract ops.
4657 return collectConcatOps(V.getNode(), Ops, DAG);
4658}
4659
4660static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4661 const SDLoc &dl) {
4662 EVT VT = Op.getValueType();
4663 unsigned NumElems = VT.getVectorNumElements();
4664 unsigned SizeInBits = VT.getSizeInBits();
4665 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4666 "Can't split odd sized vector");
4667
4669 if (collectConcatOps(Op.getNode(), SubOps, DAG)) {
4670 assert((SubOps.size() % 2) == 0 && "Can't split odd sized vector concat");
4671 unsigned HalfOps = SubOps.size() / 2;
4672 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
4673 SmallVector<SDValue, 2> LoOps(SubOps.begin(), SubOps.begin() + HalfOps);
4674 SmallVector<SDValue, 2> HiOps(SubOps.begin() + HalfOps, SubOps.end());
4675 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, LoOps);
4676 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, HiOps);
4677 return std::make_pair(Lo, Hi);
4678 }
4679
4680 // If this is a splat value (with no-undefs) then use the lower subvector,
4681 // which should be a free extraction.
4682 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4683 if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4684 return std::make_pair(Lo, Lo);
4685
4686 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4687 return std::make_pair(Lo, Hi);
4688}
4689
4690/// Break an operation into 2 half sized ops and then concatenate the results.
4692 unsigned NumOps = Op.getNumOperands();
4693 EVT VT = Op.getValueType();
4694
4695 // Extract the LHS Lo/Hi vectors
4698 for (unsigned I = 0; I != NumOps; ++I) {
4699 SDValue SrcOp = Op.getOperand(I);
4700 if (!SrcOp.getValueType().isVector()) {
4701 LoOps[I] = HiOps[I] = SrcOp;
4702 continue;
4703 }
4704 std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4705 }
4706
4707 EVT LoVT, HiVT;
4708 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4709 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4710 DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4711 DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4712}
4713
4714/// Break an unary integer operation into 2 half sized ops and then
4715/// concatenate the result back.
4717 const SDLoc &dl) {
4718 // Make sure we only try to split 256/512-bit types to avoid creating
4719 // narrow vectors.
4720 [[maybe_unused]] EVT VT = Op.getValueType();
4721 assert((Op.getOperand(0).getValueType().is256BitVector() ||
4722 Op.getOperand(0).getValueType().is512BitVector()) &&
4723 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4724 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4725 VT.getVectorNumElements() &&
4726 "Unexpected VTs!");
4727 return splitVectorOp(Op, DAG, dl);
4728}
4729
4730/// Break a binary integer operation into 2 half sized ops and then
4731/// concatenate the result back.
4733 const SDLoc &dl) {
4734 // Assert that all the types match.
4735 [[maybe_unused]] EVT VT = Op.getValueType();
4736 assert(Op.getOperand(0).getValueType() == VT &&
4737 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4738 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4739 return splitVectorOp(Op, DAG, dl);
4740}
4741
4742// Helper for splitting operands of an operation to legal target size and
4743// apply a function on each part.
4744// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4745// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4746// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4747// The argument Builder is a function that will be applied on each split part:
4748// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4749template <typename F>
4751 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4752 F Builder, bool CheckBWI = true,
4753 bool AllowAVX512 = true) {
4754 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4755 unsigned NumSubs = 1;
4756 if (AllowAVX512 && ((CheckBWI && Subtarget.useBWIRegs()) ||
4757 (!CheckBWI && Subtarget.useAVX512Regs()))) {
4758 if (VT.getSizeInBits() > 512) {
4759 NumSubs = VT.getSizeInBits() / 512;
4760 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4761 }
4762 } else if (Subtarget.hasAVX2()) {
4763 if (VT.getSizeInBits() > 256) {
4764 NumSubs = VT.getSizeInBits() / 256;
4765 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4766 }
4767 } else {
4768 if (VT.getSizeInBits() > 128) {
4769 NumSubs = VT.getSizeInBits() / 128;
4770 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4771 }
4772 }
4773
4774 if (NumSubs == 1)
4775 return Builder(DAG, DL, Ops);
4776
4778 for (unsigned i = 0; i != NumSubs; ++i) {
4780 for (SDValue Op : Ops) {
4781 EVT OpVT = Op.getValueType();
4782 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4783 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4784 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4785 }
4786 Subs.push_back(Builder(DAG, DL, SubOps));
4787 }
4788 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4789}
4790
4791// Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4792// targets.
4793static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4795 const X86Subtarget &Subtarget) {
4796 assert(Subtarget.hasAVX512() && "AVX512 target expected");
4797 MVT SVT = VT.getScalarType();
4798
4799 // If we have a 32/64 splatted constant, splat it to DstTy to
4800 // encourage a foldable broadcast'd operand.
4801 auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4802 unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4803 // AVX512 broadcasts 32/64-bit operands.
4804 // TODO: Support float once getAVX512Node is used by fp-ops.
4805 if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4807 return SDValue();
4808 // If we're not widening, don't bother if we're not bitcasting.
4809 if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4810 return SDValue();
4812 APInt SplatValue, SplatUndef;
4813 unsigned SplatBitSize;
4814 bool HasAnyUndefs;
4815 if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4816 HasAnyUndefs, OpEltSizeInBits) &&
4817 !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4818 return DAG.getConstant(SplatValue, DL, DstVT);
4819 }
4820 return SDValue();
4821 };
4822
4823 bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4824
4825 MVT DstVT = VT;
4826 if (Widen)
4827 DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4828
4829 // Canonicalize src operands.
4830 SmallVector<SDValue> SrcOps(Ops);
4831 for (SDValue &Op : SrcOps) {
4832 MVT OpVT = Op.getSimpleValueType();
4833 // Just pass through scalar operands.
4834 if (!OpVT.isVector())
4835 continue;
4836 assert(OpVT == VT && "Vector type mismatch");
4837
4838 if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4839 Op = BroadcastOp;
4840 continue;
4841 }
4842
4843 // Just widen the subvector by inserting into an undef wide vector.
4844 if (Widen)
4845 Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4846 }
4847
4848 SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4849
4850 // Perform the 512-bit op then extract the bottom subvector.
4851 if (Widen)
4852 Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4853 return Res;
4854}
4855
4856/// Insert i1-subvector to i1-vector.
4858 const X86Subtarget &Subtarget) {
4859
4860 SDLoc dl(Op);
4861 SDValue Vec = Op.getOperand(0);
4862 SDValue SubVec = Op.getOperand(1);
4863 SDValue Idx = Op.getOperand(2);
4864 unsigned IdxVal = Op.getConstantOperandVal(2);
4865
4866 // Inserting undef is a nop. We can just return the original vector.
4867 if (SubVec.isUndef())
4868 return Vec;
4869
4870 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4871 return Op;
4872
4873 MVT OpVT = Op.getSimpleValueType();
4874 unsigned NumElems = OpVT.getVectorNumElements();
4875 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, dl);
4876
4877 // Extend to natively supported kshift.
4878 MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4879
4880 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4881 // if necessary.
4882 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4883 // May need to promote to a legal type.
4884 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4885 DAG.getConstant(0, dl, WideOpVT),
4886 SubVec, Idx);
4887 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4888 }
4889
4890 MVT SubVecVT = SubVec.getSimpleValueType();
4891 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4892 assert(IdxVal + SubVecNumElems <= NumElems &&
4893 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4894 "Unexpected index value in INSERT_SUBVECTOR");
4895
4896 SDValue Undef = DAG.getUNDEF(WideOpVT);
4897
4898 if (IdxVal == 0) {
4899 // Zero lower bits of the Vec
4900 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4901 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4902 ZeroIdx);
4903 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4904 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4905 // Merge them together, SubVec should be zero extended.
4906 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4907 DAG.getConstant(0, dl, WideOpVT),
4908 SubVec, ZeroIdx);
4909 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4910 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4911 }
4912
4913 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4914 Undef, SubVec, ZeroIdx);
4915
4916 if (Vec.isUndef()) {
4917 assert(IdxVal != 0 && "Unexpected index");
4918 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4919 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4920 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4921 }
4922
4924 assert(IdxVal != 0 && "Unexpected index");
4925 // If upper elements of Vec are known undef, then just shift into place.
4926 if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4927 [](SDValue V) { return V.isUndef(); })) {
4928 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4929 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4930 } else {
4931 NumElems = WideOpVT.getVectorNumElements();
4932 unsigned ShiftLeft = NumElems - SubVecNumElems;
4933 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4934 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4935 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4936 if (ShiftRight != 0)
4937 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4938 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4939 }
4940 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4941 }
4942
4943 // Simple case when we put subvector in the upper part
4944 if (IdxVal + SubVecNumElems == NumElems) {
4945 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4946 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4947 if (SubVecNumElems * 2 == NumElems) {
4948 // Special case, use legal zero extending insert_subvector. This allows
4949 // isel to optimize when bits are known zero.
4950 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4951 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4952 DAG.getConstant(0, dl, WideOpVT),
4953 Vec, ZeroIdx);
4954 } else {
4955 // Otherwise use explicit shifts to zero the bits.
4956 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4957 Undef, Vec, ZeroIdx);
4958 NumElems = WideOpVT.getVectorNumElements();
4959 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4960 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4961 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4962 }
4963 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4964 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4965 }
4966
4967 // Inserting into the middle is more complicated.
4968
4969 NumElems = WideOpVT.getVectorNumElements();
4970
4971 // Widen the vector if needed.
4972 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4973
4974 unsigned ShiftLeft = NumElems - SubVecNumElems;
4975 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4976
4977 // Do an optimization for the most frequently used types.
4978 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4979 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4980 Mask0.flipAllBits();
4981 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4982 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4983 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4984 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4985 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4986 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4987 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4988 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4989
4990 // Reduce to original width if needed.
4991 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4992 }
4993
4994 // Clear the upper bits of the subvector and move it to its insert position.
4995 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4996 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4997 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4998 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4999
5000 // Isolate the bits below the insertion point.
5001 unsigned LowShift = NumElems - IdxVal;
5002 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
5003 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5004 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
5005 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5006
5007 // Isolate the bits after the last inserted bit.
5008 unsigned HighShift = IdxVal + SubVecNumElems;
5009 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5010 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5011 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
5012 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5013
5014 // Now OR all 3 pieces together.
5015 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
5016 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
5017
5018 // Reduce to original width if needed.
5019 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5020}
5021
5023 const SDLoc &dl) {
5024 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
5025 EVT SubVT = V1.getValueType();
5026 EVT SubSVT = SubVT.getScalarType();
5027 unsigned SubNumElts = SubVT.getVectorNumElements();
5028 unsigned SubVecWidth = SubVT.getSizeInBits();
5029 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
5030 SDValue V = insertSubVector(DAG.getPOISON(VT), V1, 0, DAG, dl, SubVecWidth);
5031 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVecWidth);
5032}
5033
5034/// Returns a vector of specified type with all bits set.
5035/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5036/// Then bitcast to their original type, ensuring they get CSE'd.
5037static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5038 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5039 "Expected a 128/256/512-bit vector type");
5040 unsigned NumElts = VT.getSizeInBits() / 32;
5041 SDValue Vec = DAG.getAllOnesConstant(dl, MVT::getVectorVT(MVT::i32, NumElts));
5042 return DAG.getBitcast(VT, Vec);
5043}
5044
5045// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
5046static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
5047 switch (Opc) {
5048 case ISD::SHL:
5049 case X86ISD::VSHL:
5050 case X86ISD::VSHLI:
5051 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
5052 case ISD::SRL:
5053 case X86ISD::VSRL:
5054 case X86ISD::VSRLI:
5055 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
5056 case ISD::SRA:
5057 case X86ISD::VSRA:
5058 case X86ISD::VSRAI:
5059 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
5060 }
5061 llvm_unreachable("Unknown target vector shift node");
5062}
5063
5064/// Handle vector element shifts where the shift amount is a constant.
5065/// Takes immediate version of shift as input.
5066static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
5067 SDValue SrcOp, uint64_t ShiftAmt,
5068 SelectionDAG &DAG) {
5069 assert(
5070 (Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) &&
5071 "Unknown target vector shift-by-constant node");
5072
5073 // Bitcast the source vector to the output type, this is mainly necessary for
5074 // vXi8/vXi64 shifts.
5075 SrcOp = DAG.getBitcast(VT, SrcOp);
5076
5077 // Fold this packed shift into its first operand if ShiftAmt is 0.
5078 if (ShiftAmt == 0)
5079 return SrcOp;
5080
5081 // Check for ShiftAmt >= element width
5082 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5083 if (ShiftAmt >= EltSizeInBits) {
5084 if (Opc == X86ISD::VSRAI)
5085 ShiftAmt = EltSizeInBits - 1;
5086 else
5087 return DAG.getConstant(0, dl, VT);
5088 }
5089
5090 // Fold this packed vector shift into a build vector if SrcOp is a
5091 // vector of Constants or UNDEFs.
5093 unsigned ShiftOpc;
5094 switch (Opc) {
5095 default:
5096 llvm_unreachable("Unknown opcode!");
5097 case X86ISD::VSHLI:
5098 ShiftOpc = ISD::SHL;
5099 break;
5100 case X86ISD::VSRLI:
5101 ShiftOpc = ISD::SRL;
5102 break;
5103 case X86ISD::VSRAI:
5104 ShiftOpc = ISD::SRA;
5105 break;
5106 }
5107
5108 SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
5109 if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
5110 return C;
5111 }
5112
5113 return DAG.getNode(Opc, dl, VT, SrcOp,
5114 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
5115}
5116
5117/// Handle vector element shifts by a splat shift amount
5118static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
5119 SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
5120 const X86Subtarget &Subtarget,
5121 SelectionDAG &DAG) {
5122 MVT AmtVT = ShAmt.getSimpleValueType();
5123 assert(AmtVT.isVector() && "Vector shift type mismatch");
5124 assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
5125 "Illegal vector splat index");
5126
5127 // Move the splat element to the bottom element.
5128 if (ShAmtIdx != 0) {
5129 SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
5130 Mask[0] = ShAmtIdx;
5131 ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
5132 }
5133
5134 // Peek through any zext node if we can get back to a 128-bit source.
5135 if (AmtVT.getScalarSizeInBits() == 64 &&
5136 (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
5138 ShAmt.getOperand(0).getValueType().isSimple() &&
5139 ShAmt.getOperand(0).getValueType().is128BitVector()) {
5140 ShAmt = ShAmt.getOperand(0);
5141 AmtVT = ShAmt.getSimpleValueType();
5142 }
5143
5144 // See if we can mask off the upper elements using the existing source node.
5145 // The shift uses the entire lower 64-bits of the amount vector, so no need to
5146 // do this for vXi64 types.
5147 bool IsMasked = false;
5148 if (AmtVT.getScalarSizeInBits() < 64) {
5149 if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
5150 ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5151 // If the shift amount has come from a scalar, then zero-extend the scalar
5152 // before moving to the vector.
5153 ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
5154 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
5155 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
5156 AmtVT = MVT::v4i32;
5157 IsMasked = true;
5158 } else if (ShAmt.getOpcode() == ISD::AND) {
5159 // See if the shift amount is already masked (e.g. for rotation modulo),
5160 // then we can zero-extend it by setting all the other mask elements to
5161 // zero.
5162 SmallVector<SDValue> MaskElts(
5163 AmtVT.getVectorNumElements(),
5164 DAG.getConstant(0, dl, AmtVT.getScalarType()));
5165 MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
5166 SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
5167 if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
5168 {ShAmt.getOperand(1), Mask}))) {
5169 ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
5170 IsMasked = true;
5171 }
5172 }
5173 }
5174
5175 // Extract if the shift amount vector is larger than 128-bits.
5176 if (AmtVT.getSizeInBits() > 128) {
5177 ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
5178 AmtVT = ShAmt.getSimpleValueType();
5179 }
5180
5181 // Zero-extend bottom element to v2i64 vector type, either by extension or
5182 // shuffle masking.
5183 if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
5184 if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
5185 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
5186 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
5187 } else if (Subtarget.hasSSE41()) {
5188 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
5189 MVT::v2i64, ShAmt);
5190 } else {
5191 SDValue ByteShift = DAG.getTargetConstant(
5192 (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
5193 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
5194 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5195 ByteShift);
5196 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5197 ByteShift);
5198 }
5199 }
5200
5201 // Change opcode to non-immediate version.
5203
5204 // The return type has to be a 128-bit type with the same element
5205 // type as the input type.
5206 MVT EltVT = VT.getVectorElementType();
5207 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
5208
5209 ShAmt = DAG.getBitcast(ShVT, ShAmt);
5210 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
5211}
5212
5213static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
5214 SDValue In, SelectionDAG &DAG) {
5215 EVT InVT = In.getValueType();
5216 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
5217
5218 // Canonicalize Opcode to general extension version.
5219 switch (Opcode) {
5220 case ISD::ANY_EXTEND:
5222 Opcode = ISD::ANY_EXTEND;
5223 break;
5224 case ISD::SIGN_EXTEND:
5226 Opcode = ISD::SIGN_EXTEND;
5227 break;
5228 case ISD::ZERO_EXTEND:
5230 Opcode = ISD::ZERO_EXTEND;
5231 break;
5232 default:
5233 llvm_unreachable("Unknown extension opcode");
5234 }
5235
5236 // For 256-bit vectors, we only need the lower (128-bit) input half.
5237 // For 512-bit vectors, we only need the lower input half or quarter.
5238 if (InVT.getSizeInBits() > 128) {
5239 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
5240 "Expected VTs to be the same size!");
5241 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5242 In = extractSubVector(In, 0, DAG, DL,
5243 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
5244 InVT = In.getValueType();
5245 }
5246
5247 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
5248 Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
5249
5250 return DAG.getNode(Opcode, DL, VT, In);
5251}
5252
5253// Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
5255 SDValue Mask, SelectionDAG &DAG) {
5256 LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
5257 RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
5258 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5259}
5260
5262 bool Lo, bool Unary) {
5263 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
5264 "Illegal vector type to unpack");
5265 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5266 int NumElts = VT.getVectorNumElements();
5267 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
5268 for (int i = 0; i < NumElts; ++i) {
5269 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
5270 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
5271 Pos += (Unary ? 0 : NumElts * (i % 2));
5272 Pos += (Lo ? 0 : NumEltsInLane / 2);
5273 Mask.push_back(Pos);
5274 }
5275}
5276
5277/// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
5278/// imposed by AVX and specific to the unary pattern. Example:
5279/// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
5280/// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
5282 bool Lo) {
5283 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5284 int NumElts = VT.getVectorNumElements();
5285 for (int i = 0; i < NumElts; ++i) {
5286 int Pos = i / 2;
5287 Pos += (Lo ? 0 : NumElts / 2);
5288 Mask.push_back(Pos);
5289 }
5290}
5291
5292// Attempt to constant fold, else just create a VECTOR_SHUFFLE.
5293static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
5294 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
5295 if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
5297 SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
5298 for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
5299 int M = Mask[I];
5300 if (M < 0)
5301 continue;
5302 SDValue V = (M < NumElts) ? V1 : V2;
5303 if (V.isUndef())
5304 continue;
5305 Ops[I] = V.getOperand(M % NumElts);
5306 }
5307 return DAG.getBuildVector(VT, dl, Ops);
5308 }
5309
5310 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5311}
5312
5313/// Returns a vector_shuffle node for an unpackl/h operation.
5314static SDValue getUnpack(SelectionDAG &DAG, const SDLoc &dl, EVT VT, SDValue V1,
5315 SDValue V2, bool UnpackHiHalf) {
5317 createUnpackShuffleMask(VT, Mask, /*Lo=*/!UnpackHiHalf, /*Unary=*/false);
5318 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5319}
5320
5321/// Returns a vector_shuffle node for an unpackl operation.
5322static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5323 SDValue V1, SDValue V2) {
5324 return getUnpack(DAG, dl, VT, V1, V2, /*UnpackHiHalf=*/false);
5325}
5326
5327/// Returns a vector_shuffle node for an unpackh operation.
5328static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5329 SDValue V1, SDValue V2) {
5330 return getUnpack(DAG, dl, VT, V1, V2, /*UnpackHiHalf=*/true);
5331}
5332
5333/// Returns a node that packs the LHS + RHS nodes together at half width.
5334/// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
5335/// TODO: Add subvector splitting if/when we have a need for it.
5336static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5337 const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
5338 bool PackHiHalf = false) {
5339 MVT OpVT = LHS.getSimpleValueType();
5340 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5341 bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
5342 assert(OpVT == RHS.getSimpleValueType() &&
5343 VT.getSizeInBits() == OpVT.getSizeInBits() &&
5344 (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
5345 "Unexpected PACK operand types");
5346 assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
5347 "Unexpected PACK result type");
5348
5349 // Rely on vector shuffles for vXi64 -> vXi32 packing.
5350 if (EltSizeInBits == 32) {
5351 SmallVector<int> PackMask;
5352 int Offset = PackHiHalf ? 1 : 0;
5353 int NumElts = VT.getVectorNumElements();
5354 for (int I = 0; I != NumElts; I += 4) {
5355 PackMask.push_back(I + Offset);
5356 PackMask.push_back(I + Offset + 2);
5357 PackMask.push_back(I + Offset + NumElts);
5358 PackMask.push_back(I + Offset + NumElts + 2);
5359 }
5360 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
5361 DAG.getBitcast(VT, RHS), PackMask);
5362 }
5363
5364 // See if we already have sufficient leading bits for PACKSS/PACKUS.
5365 if (!PackHiHalf) {
5366 if (UsePackUS &&
5367 DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
5368 DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
5369 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5370
5371 if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
5372 DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
5373 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5374 }
5375
5376 // Fallback to sign/zero extending the requested half and pack.
5377 SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
5378 if (UsePackUS) {
5379 if (PackHiHalf) {
5380 LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
5381 RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
5382 } else {
5383 SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
5384 LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
5385 RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
5386 };
5387 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5388 };
5389
5390 if (!PackHiHalf) {
5391 LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
5392 RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
5393 }
5394 LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
5395 RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
5396 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5397}
5398
5399/// Return a vector_shuffle of the specified vector of zero or undef vector.
5400/// This produces a shuffle where the low element of V2 is swizzled into the
5401/// zero/undef vector, landing at element Idx.
5402/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5404 bool IsZero,
5405 const X86Subtarget &Subtarget,
5406 SelectionDAG &DAG) {
5407 MVT VT = V2.getSimpleValueType();
5408 SDValue V1 = IsZero
5409 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5410 int NumElems = VT.getVectorNumElements();
5411 SmallVector<int, 16> MaskVec(NumElems);
5412 for (int i = 0; i != NumElems; ++i)
5413 // If this is the insertion idx, put the low elt of V2 here.
5414 MaskVec[i] = (i == Idx) ? NumElems : i;
5415 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5416}
5417
5419 if (Ptr.getOpcode() == X86ISD::Wrapper ||
5420 Ptr.getOpcode() == X86ISD::WrapperRIP)
5421 Ptr = Ptr.getOperand(0);
5422 return dyn_cast<ConstantPoolSDNode>(Ptr);
5423}
5424
5425// TODO: Add support for non-zero offsets.
5428 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5429 return nullptr;
5430 return CNode->getConstVal();
5431}
5432
5434 if (!Load || !ISD::isNormalLoad(Load))
5435 return nullptr;
5436 return getTargetConstantFromBasePtr(Load->getBasePtr());
5437}
5438
5443
5444const Constant *
5446 assert(LD && "Unexpected null LoadSDNode");
5447 return getTargetConstantFromNode(LD);
5448}
5449
5451 // Do not fold (vselect not(C), X, 0s) to (vselect C, Os, X)
5452 SDValue Cond = N->getOperand(0);
5453 SDValue RHS = N->getOperand(2);
5454 EVT CondVT = Cond.getValueType();
5455 return N->getOpcode() == ISD::VSELECT && Subtarget.hasAVX512() &&
5456 CondVT.getVectorElementType() == MVT::i1 &&
5457 ISD::isBuildVectorAllZeros(RHS.getNode());
5458}
5459
5460// Extract raw constant bits from constant pools.
5461static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5462 APInt &UndefElts,
5463 SmallVectorImpl<APInt> &EltBits,
5464 bool AllowWholeUndefs = true,
5465 bool AllowPartialUndefs = false) {
5466 assert(EltBits.empty() && "Expected an empty EltBits vector");
5467
5469
5470 EVT VT = Op.getValueType();
5471 unsigned SizeInBits = VT.getSizeInBits();
5472 unsigned NumElts = SizeInBits / EltSizeInBits;
5473
5474 // Can't split constant.
5475 if ((SizeInBits % EltSizeInBits) != 0)
5476 return false;
5477
5478 // Bitcast a source array of element bits to the target size.
5479 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5480 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5481 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5482 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
5483 "Constant bit sizes don't match");
5484
5485 // Don't split if we don't allow undef bits.
5486 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5487 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5488 return false;
5489
5490 // If we're already the right size, don't bother bitcasting.
5491 if (NumSrcElts == NumElts) {
5492 UndefElts = UndefSrcElts;
5493 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5494 return true;
5495 }
5496
5497 // Extract all the undef/constant element data and pack into single bitsets.
5498 APInt UndefBits(SizeInBits, 0);
5499 APInt MaskBits(SizeInBits, 0);
5500
5501 for (unsigned i = 0; i != NumSrcElts; ++i) {
5502 unsigned BitOffset = i * SrcEltSizeInBits;
5503 if (UndefSrcElts[i])
5504 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5505 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5506 }
5507
5508 // Split the undef/constant single bitset data into the target elements.
5509 UndefElts = APInt(NumElts, 0);
5510 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5511
5512 for (unsigned i = 0; i != NumElts; ++i) {
5513 unsigned BitOffset = i * EltSizeInBits;
5514 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5515
5516 // Only treat an element as UNDEF if all bits are UNDEF.
5517 if (UndefEltBits.isAllOnes()) {
5518 if (!AllowWholeUndefs)
5519 return false;
5520 UndefElts.setBit(i);
5521 continue;
5522 }
5523
5524 // If only some bits are UNDEF then treat them as zero (or bail if not
5525 // supported).
5526 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5527 return false;
5528
5529 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
5530 }
5531 return true;
5532 };
5533
5534 // Collect constant bits and insert into mask/undef bit masks.
5535 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5536 unsigned UndefBitIndex) {
5537 if (!Cst)
5538 return false;
5539 if (isa<UndefValue>(Cst)) {
5540 Undefs.setBit(UndefBitIndex);
5541 return true;
5542 }
5543 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5544 Mask = APInt::getSplat(CInt->getType()->getPrimitiveSizeInBits(),
5545 CInt->getValue());
5546 return true;
5547 }
5548 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5549 Mask = APInt::getSplat(CFP->getType()->getPrimitiveSizeInBits(),
5550 CFP->getValueAPF().bitcastToAPInt());
5551 return true;
5552 }
5553 if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
5554 Type *Ty = CDS->getType();
5555 if (Ty->isVectorTy()) {
5556 Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
5557 Type *EltTy = CDS->getElementType();
5558 bool IsInteger = EltTy->isIntegerTy();
5559 bool IsFP =
5560 EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
5561 if (!IsInteger && !IsFP)
5562 return false;
5563 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
5564 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
5565 if (IsInteger)
5566 Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
5567 else
5568 Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
5569 I * EltBits);
5570 return true;
5571 }
5572 }
5573 return false;
5574 };
5575
5576 // Handle UNDEFs.
5577 if (Op.isUndef()) {
5578 APInt UndefSrcElts = APInt::getAllOnes(NumElts);
5579 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5580 return CastBitData(UndefSrcElts, SrcEltBits);
5581 }
5582
5583 // Extract scalar constant bits.
5584 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5585 APInt UndefSrcElts = APInt::getZero(1);
5586 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5587 return CastBitData(UndefSrcElts, SrcEltBits);
5588 }
5589 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5590 APInt UndefSrcElts = APInt::getZero(1);
5591 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5592 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5593 return CastBitData(UndefSrcElts, SrcEltBits);
5594 }
5595
5596 // Extract constant bits from build vector.
5597 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5598 BitVector Undefs;
5599 SmallVector<APInt> SrcEltBits;
5600 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5601 if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
5602 APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
5603 for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
5604 if (Undefs[I])
5605 UndefSrcElts.setBit(I);
5606 return CastBitData(UndefSrcElts, SrcEltBits);
5607 }
5608 }
5609
5610 // Extract constant bits from constant pool vector.
5611 if (auto *Cst = getTargetConstantFromNode(Op)) {
5612 Type *CstTy = Cst->getType();
5613 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5614 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5615 return false;
5616
5617 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5618 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5619 if ((SizeInBits % SrcEltSizeInBits) != 0)
5620 return false;
5621
5622 APInt UndefSrcElts(NumSrcElts, 0);
5623 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5624 for (unsigned i = 0; i != NumSrcElts; ++i)
5625 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5626 UndefSrcElts, i))
5627 return false;
5628
5629 return CastBitData(UndefSrcElts, SrcEltBits);
5630 }
5631
5632 // Extract constant bits from a broadcasted constant pool scalar.
5633 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
5634 EltSizeInBits <= VT.getScalarSizeInBits()) {
5635 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5636 if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
5637 return false;
5638
5639 SDValue Ptr = MemIntr->getBasePtr();
5640 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
5641 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5642 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5643
5644 APInt UndefSrcElts(NumSrcElts, 0);
5645 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5646 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
5647 if (UndefSrcElts[0])
5648 UndefSrcElts.setBits(0, NumSrcElts);
5649 if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
5650 SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
5651 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5652 return CastBitData(UndefSrcElts, SrcEltBits);
5653 }
5654 }
5655 }
5656
5657 // Extract constant bits from a subvector broadcast.
5658 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
5659 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5660 SDValue Ptr = MemIntr->getBasePtr();
5661 // The source constant may be larger than the subvector broadcast,
5662 // ensure we extract the correct subvector constants.
5663 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
5664 Type *CstTy = Cst->getType();
5665 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5666 unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
5667 if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
5668 (SizeInBits % SubVecSizeInBits) != 0)
5669 return false;
5670 unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
5671 unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
5672 unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
5673 APInt UndefSubElts(NumSubElts, 0);
5674 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
5675 APInt(CstEltSizeInBits, 0));
5676 for (unsigned i = 0; i != NumSubElts; ++i) {
5677 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
5678 UndefSubElts, i))
5679 return false;
5680 for (unsigned j = 1; j != NumSubVecs; ++j)
5681 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
5682 }
5683 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
5684 UndefSubElts);
5685 return CastBitData(UndefSubElts, SubEltBits);
5686 }
5687 }
5688
5689 // Extract a rematerialized scalar constant insertion.
5690 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5691 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5692 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5693 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5694 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5695
5696 APInt UndefSrcElts(NumSrcElts, 0);
5697 SmallVector<APInt, 64> SrcEltBits;
5698 const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
5699 SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
5700 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5701 return CastBitData(UndefSrcElts, SrcEltBits);
5702 }
5703
5704 // Insert constant bits from a base and sub vector sources.
5705 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
5706 // If bitcasts to larger elements we might lose track of undefs - don't
5707 // allow any to be safe.
5708 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5709 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
5710
5711 APInt UndefSrcElts, UndefSubElts;
5712 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
5713 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
5714 UndefSubElts, EltSubBits,
5715 AllowWholeUndefs && AllowUndefs,
5716 AllowPartialUndefs && AllowUndefs) &&
5717 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
5718 UndefSrcElts, EltSrcBits,
5719 AllowWholeUndefs && AllowUndefs,
5720 AllowPartialUndefs && AllowUndefs)) {
5721 unsigned BaseIdx = Op.getConstantOperandVal(2);
5722 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
5723 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
5724 EltSrcBits[BaseIdx + i] = EltSubBits[i];
5725 return CastBitData(UndefSrcElts, EltSrcBits);
5726 }
5727 }
5728
5729 // Extract constant bits from a subvector's source.
5730 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5731 getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits, UndefElts,
5732 EltBits, AllowWholeUndefs,
5733 AllowPartialUndefs)) {
5734 EVT SrcVT = Op.getOperand(0).getValueType();
5735 unsigned NumSrcElts = SrcVT.getSizeInBits() / EltSizeInBits;
5736 unsigned NumSubElts = VT.getSizeInBits() / EltSizeInBits;
5737 unsigned BaseOfs = Op.getConstantOperandVal(1) * VT.getScalarSizeInBits();
5738 unsigned BaseIdx = BaseOfs / EltSizeInBits;
5739 assert((SrcVT.getSizeInBits() % EltSizeInBits) == 0 &&
5740 (VT.getSizeInBits() % EltSizeInBits) == 0 &&
5741 (BaseOfs % EltSizeInBits) == 0 && "Bad subvector index");
5742
5743 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5744 if ((BaseIdx + NumSubElts) != NumSrcElts)
5745 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5746 if (BaseIdx != 0)
5747 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5748 return true;
5749 }
5750
5751 // Extract constant bits from shuffle node sources.
5752 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5753 // TODO - support shuffle through bitcasts.
5754 if (EltSizeInBits != VT.getScalarSizeInBits())
5755 return false;
5756
5757 ArrayRef<int> Mask = SVN->getMask();
5758 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5759 llvm::any_of(Mask, [](int M) { return M < 0; }))
5760 return false;
5761
5762 APInt UndefElts0, UndefElts1;
5763 SmallVector<APInt, 32> EltBits0, EltBits1;
5764 if (isAnyInRange(Mask, 0, NumElts) &&
5765 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5766 UndefElts0, EltBits0, AllowWholeUndefs,
5767 AllowPartialUndefs))
5768 return false;
5769 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5770 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5771 UndefElts1, EltBits1, AllowWholeUndefs,
5772 AllowPartialUndefs))
5773 return false;
5774
5775 UndefElts = APInt::getZero(NumElts);
5776 for (int i = 0; i != (int)NumElts; ++i) {
5777 int M = Mask[i];
5778 if (M < 0) {
5779 UndefElts.setBit(i);
5780 EltBits.push_back(APInt::getZero(EltSizeInBits));
5781 } else if (M < (int)NumElts) {
5782 if (UndefElts0[M])
5783 UndefElts.setBit(i);
5784 EltBits.push_back(EltBits0[M]);
5785 } else {
5786 if (UndefElts1[M - NumElts])
5787 UndefElts.setBit(i);
5788 EltBits.push_back(EltBits1[M - NumElts]);
5789 }
5790 }
5791 return true;
5792 }
5793
5794 return false;
5795}
5796
5797namespace llvm {
5798namespace X86 {
5799bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
5800 APInt UndefElts;
5801 SmallVector<APInt, 16> EltBits;
5803 Op, Op.getScalarValueSizeInBits(), UndefElts, EltBits,
5804 /*AllowWholeUndefs*/ true, AllowPartialUndefs)) {
5805 int SplatIndex = -1;
5806 for (int i = 0, e = EltBits.size(); i != e; ++i) {
5807 if (UndefElts[i])
5808 continue;
5809 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5810 SplatIndex = -1;
5811 break;
5812 }
5813 SplatIndex = i;
5814 }
5815 if (0 <= SplatIndex) {
5816 SplatVal = EltBits[SplatIndex];
5817 return true;
5818 }
5819 }
5820
5821 return false;
5822}
5823
5824int getRoundingModeX86(unsigned RM) {
5825 switch (static_cast<::llvm::RoundingMode>(RM)) {
5826 // clang-format off
5827 case ::llvm::RoundingMode::NearestTiesToEven: return X86::rmToNearest;
5828 case ::llvm::RoundingMode::TowardNegative: return X86::rmDownward;
5829 case ::llvm::RoundingMode::TowardPositive: return X86::rmUpward;
5830 case ::llvm::RoundingMode::TowardZero: return X86::rmTowardZero;
5831 default: return X86::rmInvalid;
5832 // clang-format on
5833 }
5834}
5835
5836} // namespace X86
5837} // namespace llvm
5838
5840 unsigned MaskEltSizeInBits,
5842 APInt &UndefElts) {
5843 // Extract the raw target constant bits.
5844 SmallVector<APInt, 64> EltBits;
5845 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5846 EltBits, /* AllowWholeUndefs */ true,
5847 /* AllowPartialUndefs */ false))
5848 return false;
5849
5850 // Insert the extracted elements into the mask.
5851 for (const APInt &Elt : EltBits)
5852 RawMask.push_back(Elt.getZExtValue());
5853
5854 return true;
5855}
5856
5857static bool isConstantPowerOf2(SDValue V, unsigned EltSizeInBIts,
5858 bool AllowUndefs) {
5859 APInt UndefElts;
5860 SmallVector<APInt, 64> EltBits;
5861 if (!getTargetConstantBitsFromNode(V, EltSizeInBIts, UndefElts, EltBits,
5862 /*AllowWholeUndefs*/ AllowUndefs,
5863 /*AllowPartialUndefs*/ false))
5864 return false;
5865
5866 bool IsPow2OrUndef = true;
5867 for (unsigned I = 0, E = EltBits.size(); I != E; ++I)
5868 IsPow2OrUndef &= UndefElts[I] || EltBits[I].isPowerOf2();
5869 return IsPow2OrUndef;
5870}
5871
5872// Helper to attempt to return a cheaper, bit-inverted version of \p V.
5874 // TODO: don't always ignore oneuse constraints.
5875 V = peekThroughBitcasts(V);
5876 EVT VT = V.getValueType();
5877
5878 // Match not(xor X, -1) -> X.
5879 if (V.getOpcode() == ISD::XOR &&
5880 (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
5881 isAllOnesConstant(V.getOperand(1))))
5882 return V.getOperand(0);
5883
5884 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
5885 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5886 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5887 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5888 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5889 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
5890 V.getOperand(1));
5891 }
5892 }
5893
5894 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
5895 if (V.getOpcode() == X86ISD::PCMPGT &&
5896 !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
5897 !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
5898 V.getOperand(0).hasOneUse()) {
5899 APInt UndefElts;
5900 SmallVector<APInt> EltBits;
5901 if (getTargetConstantBitsFromNode(V.getOperand(0),
5902 V.getScalarValueSizeInBits(), UndefElts,
5903 EltBits) &&
5904 !ISD::isBuildVectorOfConstantSDNodes(V.getOperand(1).getNode())) {
5905 // Don't fold min_signed_value -> (min_signed_value - 1)
5906 bool MinSigned = false;
5907 for (APInt &Elt : EltBits) {
5908 MinSigned |= Elt.isMinSignedValue();
5909 Elt -= 1;
5910 }
5911 if (!MinSigned) {
5912 SDLoc DL(V);
5913 MVT VT = V.getSimpleValueType();
5914 return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5915 getConstVector(EltBits, UndefElts, VT, DAG, DL));
5916 }
5917 }
5918 }
5919
5920 // Match not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
5922 if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5923 for (SDValue &CatOp : CatOps) {
5924 SDValue NotCat = IsNOT(CatOp, DAG);
5925 if (!NotCat)
5926 return SDValue();
5927 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5928 }
5929 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), VT, CatOps);
5930 }
5931
5932 // Match not(or(not(X),not(Y))) -> and(X, Y).
5933 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
5934 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
5935 // TODO: Handle cases with single NOT operand -> ANDNP
5936 if (SDValue Op1 = IsNOT(V.getOperand(1), DAG))
5937 if (SDValue Op0 = IsNOT(V.getOperand(0), DAG))
5938 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
5939 DAG.getBitcast(VT, Op1));
5940 }
5941
5942 return SDValue();
5943}
5944
5945/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5946/// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5947/// Note: This ignores saturation, so inputs must be checked first.
5949 bool Unary, unsigned NumStages = 1) {
5950 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5951 unsigned NumElts = VT.getVectorNumElements();
5952 unsigned NumLanes = VT.getSizeInBits() / 128;
5953 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5954 unsigned Offset = Unary ? 0 : NumElts;
5955 unsigned Repetitions = 1u << (NumStages - 1);
5956 unsigned Increment = 1u << NumStages;
5957 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5958
5959 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5960 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5961 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5962 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5963 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5964 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5965 }
5966 }
5967}
5968
5969// Split the demanded elts of a PACKSS/PACKUS node between its operands.
5970static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5971 APInt &DemandedLHS, APInt &DemandedRHS) {
5972 int NumLanes = VT.getSizeInBits() / 128;
5973 int NumElts = DemandedElts.getBitWidth();
5974 int NumInnerElts = NumElts / 2;
5975 int NumEltsPerLane = NumElts / NumLanes;
5976 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5977
5978 DemandedLHS = APInt::getZero(NumInnerElts);
5979 DemandedRHS = APInt::getZero(NumInnerElts);
5980
5981 // Map DemandedElts to the packed operands.
5982 for (int Lane = 0; Lane != NumLanes; ++Lane) {
5983 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5984 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
5985 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
5986 if (DemandedElts[OuterIdx])
5987 DemandedLHS.setBit(InnerIdx);
5988 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
5989 DemandedRHS.setBit(InnerIdx);
5990 }
5991 }
5992}
5993
5994// Split the demanded elts of a HADD/HSUB node between its operands.
5995static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
5996 APInt &DemandedLHS, APInt &DemandedRHS) {
5998 DemandedLHS, DemandedRHS);
5999 DemandedLHS |= DemandedLHS << 1;
6000 DemandedRHS |= DemandedRHS << 1;
6001}
6002
6003/// Calculates the shuffle mask corresponding to the target-specific opcode.
6004/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6005/// operands in \p Ops, and returns true.
6006/// Sets \p IsUnary to true if only one source is used. Note that this will set
6007/// IsUnary for shuffles which use a single input multiple times, and in those
6008/// cases it will adjust the mask to only have indices within that single input.
6009/// It is an error to call this with non-empty Mask/Ops vectors.
6010static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6012 SmallVectorImpl<int> &Mask, bool &IsUnary) {
6013 if (!isTargetShuffle(N.getOpcode()))
6014 return false;
6015
6016 MVT VT = N.getSimpleValueType();
6017 unsigned NumElems = VT.getVectorNumElements();
6018 unsigned MaskEltSize = VT.getScalarSizeInBits();
6020 APInt RawUndefs;
6021 uint64_t ImmN;
6022
6023 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6024 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6025
6026 IsUnary = false;
6027 bool IsFakeUnary = false;
6028 switch (N.getOpcode()) {
6029 case X86ISD::BLENDI:
6030 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6031 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6032 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6033 DecodeBLENDMask(NumElems, ImmN, Mask);
6034 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6035 break;
6036 case X86ISD::SHUFP:
6037 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6038 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6039 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6040 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6041 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6042 break;
6043 case X86ISD::INSERTPS:
6044 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6045 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6046 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6047 DecodeINSERTPSMask(ImmN, Mask, /*SrcIsMem=*/false);
6048 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6049 break;
6050 case X86ISD::EXTRQI:
6051 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6052 if (isa<ConstantSDNode>(N.getOperand(1)) &&
6053 isa<ConstantSDNode>(N.getOperand(2))) {
6054 int BitLen = N.getConstantOperandVal(1);
6055 int BitIdx = N.getConstantOperandVal(2);
6056 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6057 IsUnary = true;
6058 }
6059 break;
6060 case X86ISD::INSERTQI:
6061 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6062 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6063 if (isa<ConstantSDNode>(N.getOperand(2)) &&
6064 isa<ConstantSDNode>(N.getOperand(3))) {
6065 int BitLen = N.getConstantOperandVal(2);
6066 int BitIdx = N.getConstantOperandVal(3);
6067 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6068 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6069 }
6070 break;
6071 case X86ISD::UNPCKH:
6072 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6073 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6074 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6075 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6076 break;
6077 case X86ISD::UNPCKL:
6078 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6079 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6080 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6081 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6082 break;
6083 case X86ISD::MOVHLPS:
6084 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6085 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6086 DecodeMOVHLPSMask(NumElems, Mask);
6087 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6088 break;
6089 case X86ISD::MOVLHPS:
6090 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6091 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6092 DecodeMOVLHPSMask(NumElems, Mask);
6093 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6094 break;
6095 case X86ISD::VALIGN:
6096 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
6097 "Only 32-bit and 64-bit elements are supported!");
6098 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6099 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6100 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6101 DecodeVALIGNMask(NumElems, ImmN, Mask);
6102 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6103 Ops.push_back(N.getOperand(1));
6104 Ops.push_back(N.getOperand(0));
6105 break;
6106 case X86ISD::PALIGNR:
6107 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6108 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6109 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6110 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6111 DecodePALIGNRMask(NumElems, ImmN, Mask);
6112 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6113 Ops.push_back(N.getOperand(1));
6114 Ops.push_back(N.getOperand(0));
6115 break;
6116 case X86ISD::VSHLDQ:
6117 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6118 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6119 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6120 DecodePSLLDQMask(NumElems, ImmN, Mask);
6121 IsUnary = true;
6122 break;
6123 case X86ISD::VSRLDQ:
6124 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6125 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6126 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6127 DecodePSRLDQMask(NumElems, ImmN, Mask);
6128 IsUnary = true;
6129 break;
6130 case X86ISD::PSHUFD:
6131 case X86ISD::VPERMILPI:
6132 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6133 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6134 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
6135 IsUnary = true;
6136 break;
6137 case X86ISD::PSHUFHW:
6138 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6139 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6140 DecodePSHUFHWMask(NumElems, ImmN, Mask);
6141 IsUnary = true;
6142 break;
6143 case X86ISD::PSHUFLW:
6144 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6145 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6146 DecodePSHUFLWMask(NumElems, ImmN, Mask);
6147 IsUnary = true;
6148 break;
6149 case X86ISD::VZEXT_MOVL:
6150 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6151 DecodeZeroMoveLowMask(NumElems, Mask);
6152 IsUnary = true;
6153 break;
6154 case X86ISD::VBROADCAST:
6155 // We only decode broadcasts of same-sized vectors, peeking through to
6156 // extracted subvectors is likely to cause hasOneUse issues with
6157 // SimplifyDemandedBits etc.
6158 if (N.getOperand(0).getValueType() == VT) {
6159 DecodeVectorBroadcast(NumElems, Mask);
6160 IsUnary = true;
6161 break;
6162 }
6163 return false;
6164 case X86ISD::VPERMILPV: {
6165 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6166 IsUnary = true;
6167 SDValue MaskNode = N.getOperand(1);
6168 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6169 RawUndefs)) {
6170 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6171 break;
6172 }
6173 return false;
6174 }
6175 case X86ISD::PSHUFB: {
6176 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6177 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6178 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6179 IsUnary = true;
6180 SDValue MaskNode = N.getOperand(1);
6181 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6182 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6183 break;
6184 }
6185 return false;
6186 }
6187 case X86ISD::VPERMI:
6188 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6189 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6190 DecodeVPERMMask(NumElems, ImmN, Mask);
6191 IsUnary = true;
6192 break;
6193 case X86ISD::MOVSS:
6194 case X86ISD::MOVSD:
6195 case X86ISD::MOVSH:
6196 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6197 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6198 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6199 break;
6200 case X86ISD::VPERM2X128:
6201 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6202 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6203 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6204 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
6205 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6206 break;
6207 case X86ISD::SHUF128:
6208 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6209 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6210 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6211 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
6212 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6213 break;
6214 case X86ISD::MOVSLDUP:
6215 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6216 DecodeMOVSLDUPMask(NumElems, Mask);
6217 IsUnary = true;
6218 break;
6219 case X86ISD::MOVSHDUP:
6220 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6221 DecodeMOVSHDUPMask(NumElems, Mask);
6222 IsUnary = true;
6223 break;
6224 case X86ISD::MOVDDUP:
6225 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6226 DecodeMOVDDUPMask(NumElems, Mask);
6227 IsUnary = true;
6228 break;
6229 case X86ISD::VPERMIL2: {
6230 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6231 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6232 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6233 SDValue MaskNode = N.getOperand(2);
6234 SDValue CtrlNode = N.getOperand(3);
6235 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6236 unsigned CtrlImm = CtrlOp->getZExtValue();
6237 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6238 RawUndefs)) {
6239 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6240 Mask);
6241 break;
6242 }
6243 }
6244 return false;
6245 }
6246 case X86ISD::VPPERM: {
6247 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6248 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6249 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6250 SDValue MaskNode = N.getOperand(2);
6251 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6252 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6253 break;
6254 }
6255 return false;
6256 }
6257 case X86ISD::VPERMV: {
6258 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6259 IsUnary = true;
6260 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6261 Ops.push_back(N.getOperand(1));
6262 SDValue MaskNode = N.getOperand(0);
6263 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6264 RawUndefs)) {
6265 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6266 break;
6267 }
6268 return false;
6269 }
6270 case X86ISD::VPERMV3: {
6271 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6272 assert(N.getOperand(2).getValueType() == VT && "Unexpected value type");
6273 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(2);
6274 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6275 Ops.push_back(N.getOperand(0));
6276 Ops.push_back(N.getOperand(2));
6277 SDValue MaskNode = N.getOperand(1);
6278 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6279 RawUndefs)) {
6280 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6281 break;
6282 }
6283 return false;
6284 }
6285 case X86ISD::COMPRESS: {
6286 SDValue CmpVec = N.getOperand(0);
6287 SDValue PassThru = N.getOperand(1);
6288 SDValue CmpMask = N.getOperand(2);
6289 APInt UndefElts;
6290 SmallVector<APInt> EltBits;
6291 if (!getTargetConstantBitsFromNode(CmpMask, 1, UndefElts, EltBits))
6292 return false;
6293 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6294 "Illegal compression mask");
6295 for (unsigned I = 0; I != NumElems; ++I) {
6296 if (!EltBits[I].isZero())
6297 Mask.push_back(I);
6298 }
6299 while (Mask.size() != NumElems) {
6300 Mask.push_back(NumElems + Mask.size());
6301 }
6302 Ops.push_back(CmpVec);
6303 Ops.push_back(PassThru);
6304 return true;
6305 }
6306 case X86ISD::EXPAND: {
6307 SDValue ExpVec = N.getOperand(0);
6308 SDValue PassThru = N.getOperand(1);
6309 SDValue ExpMask = N.getOperand(2);
6310 APInt UndefElts;
6311 SmallVector<APInt> EltBits;
6312 if (!getTargetConstantBitsFromNode(ExpMask, 1, UndefElts, EltBits))
6313 return false;
6314 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6315 "Illegal expansion mask");
6316 unsigned ExpIndex = 0;
6317 for (unsigned I = 0; I != NumElems; ++I) {
6318 if (EltBits[I].isZero())
6319 Mask.push_back(I + NumElems);
6320 else
6321 Mask.push_back(ExpIndex++);
6322 }
6323 Ops.push_back(ExpVec);
6324 Ops.push_back(PassThru);
6325 return true;
6326 }
6327 default:
6328 llvm_unreachable("unknown target shuffle node");
6329 }
6330
6331 // Empty mask indicates the decode failed.
6332 if (Mask.empty())
6333 return false;
6334
6335 // Check if we're getting a shuffle mask with zero'd elements.
6336 if (!AllowSentinelZero && isAnyZero(Mask))
6337 return false;
6338
6339 // If we have a fake unary shuffle, the shuffle mask is spread across two
6340 // inputs that are actually the same node. Re-map the mask to always point
6341 // into the first input.
6342 if (IsFakeUnary)
6343 for (int &M : Mask)
6344 if (M >= (int)Mask.size())
6345 M -= Mask.size();
6346
6347 // If we didn't already add operands in the opcode-specific code, default to
6348 // adding 1 or 2 operands starting at 0.
6349 if (Ops.empty()) {
6350 Ops.push_back(N.getOperand(0));
6351 if (!IsUnary || IsFakeUnary)
6352 Ops.push_back(N.getOperand(1));
6353 }
6354
6355 return true;
6356}
6357
6358// Wrapper for getTargetShuffleMask with InUnary;
6359static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6361 SmallVectorImpl<int> &Mask) {
6362 bool IsUnary;
6363 return getTargetShuffleMask(N, AllowSentinelZero, Ops, Mask, IsUnary);
6364}
6365
6366/// Compute whether each element of a shuffle is zeroable.
6367///
6368/// A "zeroable" vector shuffle element is one which can be lowered to zero.
6369/// Either it is an undef element in the shuffle mask, the element of the input
6370/// referenced is undef, or the element of the input referenced is known to be
6371/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6372/// as many lanes with this technique as possible to simplify the remaining
6373/// shuffle.
6375 SDValue V1, SDValue V2,
6376 APInt &KnownUndef, APInt &KnownZero) {
6377 int Size = Mask.size();
6378 KnownUndef = KnownZero = APInt::getZero(Size);
6379
6381 V2 = peekThroughBitcasts(V2);
6382
6383 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6384 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6385
6386 int VectorSizeInBits = V1.getValueSizeInBits();
6387 int ScalarSizeInBits = VectorSizeInBits / Size;
6388 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
6389
6390 for (int i = 0; i < Size; ++i) {
6391 int M = Mask[i];
6392 // Handle the easy cases.
6393 if (M < 0) {
6394 KnownUndef.setBit(i);
6395 continue;
6396 }
6397 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6398 KnownZero.setBit(i);
6399 continue;
6400 }
6401
6402 // Determine shuffle input and normalize the mask.
6403 SDValue V = M < Size ? V1 : V2;
6404 M %= Size;
6405
6406 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
6407 if (V.getOpcode() != ISD::BUILD_VECTOR)
6408 continue;
6409
6410 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
6411 // the (larger) source element must be UNDEF/ZERO.
6412 if ((Size % V.getNumOperands()) == 0) {
6413 int Scale = Size / V->getNumOperands();
6414 SDValue Op = V.getOperand(M / Scale);
6415 if (Op.isUndef())
6416 KnownUndef.setBit(i);
6417 if (X86::isZeroNode(Op))
6418 KnownZero.setBit(i);
6419 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
6420 APInt Val = Cst->getAPIntValue();
6421 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6422 if (Val == 0)
6423 KnownZero.setBit(i);
6424 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6425 APInt Val = Cst->getValueAPF().bitcastToAPInt();
6426 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6427 if (Val == 0)
6428 KnownZero.setBit(i);
6429 }
6430 continue;
6431 }
6432
6433 // If the BUILD_VECTOR has more elements then all the (smaller) source
6434 // elements must be UNDEF or ZERO.
6435 if ((V.getNumOperands() % Size) == 0) {
6436 int Scale = V->getNumOperands() / Size;
6437 bool AllUndef = true;
6438 bool AllZero = true;
6439 for (int j = 0; j < Scale; ++j) {
6440 SDValue Op = V.getOperand((M * Scale) + j);
6441 AllUndef &= Op.isUndef();
6442 AllZero &= X86::isZeroNode(Op);
6443 }
6444 if (AllUndef)
6445 KnownUndef.setBit(i);
6446 if (AllZero)
6447 KnownZero.setBit(i);
6448 continue;
6449 }
6450 }
6451}
6452
6453/// Decode a target shuffle mask and inputs and see if any values are
6454/// known to be undef or zero from their inputs.
6455/// Returns true if the target shuffle mask was decoded.
6456/// FIXME: Merge this with computeZeroableShuffleElements?
6459 APInt &KnownUndef, APInt &KnownZero) {
6460 bool IsUnary;
6461 if (!isTargetShuffle(N.getOpcode()))
6462 return false;
6463
6464 MVT VT = N.getSimpleValueType();
6465 if (!getTargetShuffleMask(N, true, Ops, Mask, IsUnary))
6466 return false;
6467
6468 int Size = Mask.size();
6469 SDValue V1 = Ops[0];
6470 SDValue V2 = IsUnary ? V1 : Ops[1];
6471 KnownUndef = KnownZero = APInt::getZero(Size);
6472
6474 V2 = peekThroughBitcasts(V2);
6475
6476 assert((VT.getSizeInBits() % Size) == 0 &&
6477 "Illegal split of shuffle value type");
6478 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
6479
6480 // Extract known constant input data.
6481 APInt UndefSrcElts[2];
6482 SmallVector<APInt, 32> SrcEltBits[2];
6483 bool IsSrcConstant[2] = {
6484 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6485 SrcEltBits[0], /*AllowWholeUndefs*/ true,
6486 /*AllowPartialUndefs*/ false),
6487 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6488 SrcEltBits[1], /*AllowWholeUndefs*/ true,
6489 /*AllowPartialUndefs*/ false)};
6490
6491 for (int i = 0; i < Size; ++i) {
6492 int M = Mask[i];
6493
6494 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6495 if (M < 0) {
6496 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
6497 if (SM_SentinelUndef == M)
6498 KnownUndef.setBit(i);
6499 if (SM_SentinelZero == M)
6500 KnownZero.setBit(i);
6501 continue;
6502 }
6503
6504 // Determine shuffle input and normalize the mask.
6505 unsigned SrcIdx = M / Size;
6506 SDValue V = M < Size ? V1 : V2;
6507 M %= Size;
6508
6509 // We are referencing an UNDEF input.
6510 if (V.isUndef()) {
6511 KnownUndef.setBit(i);
6512 continue;
6513 }
6514
6515 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6516 // TODO: We currently only set UNDEF for integer types - floats use the same
6517 // registers as vectors and many of the scalar folded loads rely on the
6518 // SCALAR_TO_VECTOR pattern.
6519 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6520 (Size % V.getValueType().getVectorNumElements()) == 0) {
6521 int Scale = Size / V.getValueType().getVectorNumElements();
6522 int Idx = M / Scale;
6523 if (Idx != 0 && !VT.isFloatingPoint())
6524 KnownUndef.setBit(i);
6525 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6526 KnownZero.setBit(i);
6527 continue;
6528 }
6529
6530 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
6531 // base vectors.
6532 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
6533 SDValue Vec = V.getOperand(0);
6534 int NumVecElts = Vec.getValueType().getVectorNumElements();
6535 if (Vec.isUndef() && Size == NumVecElts) {
6536 int Idx = V.getConstantOperandVal(2);
6537 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
6538 if (M < Idx || (Idx + NumSubElts) <= M)
6539 KnownUndef.setBit(i);
6540 }
6541 continue;
6542 }
6543
6544 // Attempt to extract from the source's constant bits.
6545 if (IsSrcConstant[SrcIdx]) {
6546 if (UndefSrcElts[SrcIdx][M])
6547 KnownUndef.setBit(i);
6548 else if (SrcEltBits[SrcIdx][M] == 0)
6549 KnownZero.setBit(i);
6550 }
6551 }
6552
6553 assert(VT.getVectorNumElements() == (unsigned)Size &&
6554 "Different mask size from vector size!");
6555 return true;
6556}
6557
6558// Replace target shuffle mask elements with known undef/zero sentinels.
6560 const APInt &KnownUndef,
6561 const APInt &KnownZero,
6562 bool ResolveKnownZeros= true) {
6563 unsigned NumElts = Mask.size();
6564 assert(KnownUndef.getBitWidth() == NumElts &&
6565 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
6566
6567 for (unsigned i = 0; i != NumElts; ++i) {
6568 if (KnownUndef[i])
6569 Mask[i] = SM_SentinelUndef;
6570 else if (ResolveKnownZeros && KnownZero[i])
6571 Mask[i] = SM_SentinelZero;
6572 }
6573}
6574
6575// Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
6577 APInt &KnownUndef,
6578 APInt &KnownZero) {
6579 unsigned NumElts = Mask.size();
6580 KnownUndef = KnownZero = APInt::getZero(NumElts);
6581
6582 for (unsigned i = 0; i != NumElts; ++i) {
6583 int M = Mask[i];
6584 if (SM_SentinelUndef == M)
6585 KnownUndef.setBit(i);
6586 if (SM_SentinelZero == M)
6587 KnownZero.setBit(i);
6588 }
6589}
6590
6591// Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
6593 SDValue Cond, bool IsBLENDV = false) {
6594 EVT CondVT = Cond.getValueType();
6595 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
6596 unsigned NumElts = CondVT.getVectorNumElements();
6597
6598 APInt UndefElts;
6599 SmallVector<APInt, 32> EltBits;
6600 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
6601 /*AllowWholeUndefs*/ true,
6602 /*AllowPartialUndefs*/ false))
6603 return false;
6604
6605 Mask.resize(NumElts, SM_SentinelUndef);
6606
6607 for (int i = 0; i != (int)NumElts; ++i) {
6608 Mask[i] = i;
6609 // Arbitrarily choose from the 2nd operand if the select condition element
6610 // is undef.
6611 // TODO: Can we do better by matching patterns such as even/odd?
6612 if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
6613 (IsBLENDV && EltBits[i].isNonNegative()))
6614 Mask[i] += NumElts;
6615 }
6616
6617 return true;
6618}
6619
6620// Forward declaration (for getFauxShuffleMask recursive check).
6621static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6624 const SelectionDAG &DAG, unsigned Depth,
6625 bool ResolveKnownElts);
6626
6627// Attempt to decode ops that could be represented as a shuffle mask.
6628// The decoded shuffle mask may contain a different number of elements to the
6629// destination value type.
6630// TODO: Merge into getTargetShuffleInputs()
6631static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
6634 const SelectionDAG &DAG, unsigned Depth,
6635 bool ResolveKnownElts) {
6636 Mask.clear();
6637 Ops.clear();
6638
6639 MVT VT = N.getSimpleValueType();
6640 unsigned NumElts = VT.getVectorNumElements();
6641 unsigned NumSizeInBits = VT.getSizeInBits();
6642 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6643 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
6644 return false;
6645 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
6646 unsigned NumSizeInBytes = NumSizeInBits / 8;
6647 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6648
6649 unsigned Opcode = N.getOpcode();
6650 switch (Opcode) {
6651 case ISD::VECTOR_SHUFFLE: {
6652 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6653 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6654 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6655 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6656 Ops.push_back(N.getOperand(0));
6657 Ops.push_back(N.getOperand(1));
6658 return true;
6659 }
6660 return false;
6661 }
6662 case ISD::AND:
6663 case X86ISD::ANDNP: {
6664 // Attempt to decode as a per-byte mask.
6665 APInt UndefElts;
6666 SmallVector<APInt, 32> EltBits;
6667 SDValue N0 = N.getOperand(0);
6668 SDValue N1 = N.getOperand(1);
6669 bool IsAndN = (X86ISD::ANDNP == Opcode);
6670 uint64_t ZeroMask = IsAndN ? 255 : 0;
6671 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits,
6672 /*AllowWholeUndefs*/ false,
6673 /*AllowPartialUndefs*/ false))
6674 return false;
6675 // We can't assume an undef src element gives an undef dst - the other src
6676 // might be zero.
6677 assert(UndefElts.isZero() && "Unexpected UNDEF element in AND/ANDNP mask");
6678 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6679 const APInt &ByteBits = EltBits[i];
6680 if (ByteBits != 0 && ByteBits != 255)
6681 return false;
6682 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6683 }
6684 Ops.push_back(IsAndN ? N1 : N0);
6685 return true;
6686 }
6687 case ISD::OR: {
6688 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6689 // is a valid shuffle index.
6690 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
6691 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
6692 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6693 return false;
6694
6695 SmallVector<int, 64> SrcMask0, SrcMask1;
6696 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6699 if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
6700 Depth + 1, true) ||
6701 !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
6702 Depth + 1, true))
6703 return false;
6704
6705 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6706 SmallVector<int, 64> Mask0, Mask1;
6707 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6708 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6709 for (int i = 0; i != (int)MaskSize; ++i) {
6710 // NOTE: Don't handle demanded SM_SentinelUndef, as we can end up in
6711 // infinite loops converting between OR and BLEND shuffles due to
6712 // canWidenShuffleElements merging away undef elements, meaning we
6713 // fail to recognise the OR as the undef element isn't known zero.
6714 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6715 Mask.push_back(SM_SentinelZero);
6716 else if (Mask1[i] == SM_SentinelZero)
6717 Mask.push_back(i);
6718 else if (Mask0[i] == SM_SentinelZero)
6719 Mask.push_back(i + MaskSize);
6720 else if (MaskSize == NumElts && !DemandedElts[i])
6721 Mask.push_back(SM_SentinelUndef);
6722 else
6723 return false;
6724 }
6725 Ops.push_back(N.getOperand(0));
6726 Ops.push_back(N.getOperand(1));
6727 return true;
6728 }
6729 case ISD::CONCAT_VECTORS: {
6730 // Limit this to vXi64 vector cases to make the most of cross lane shuffles.
6731 unsigned NumSubElts = N.getOperand(0).getValueType().getVectorNumElements();
6732 if (NumBitsPerElt == 64) {
6733 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
6734 for (unsigned M = 0; M != NumSubElts; ++M)
6735 Mask.push_back((I * NumElts) + M);
6736 Ops.push_back(N.getOperand(I));
6737 }
6738 return true;
6739 }
6740 return false;
6741 }
6742 case ISD::INSERT_SUBVECTOR: {
6743 SDValue Src = N.getOperand(0);
6744 SDValue Sub = N.getOperand(1);
6745 EVT SubVT = Sub.getValueType();
6746 unsigned NumSubElts = SubVT.getVectorNumElements();
6747 uint64_t InsertIdx = N.getConstantOperandVal(2);
6748 // Subvector isn't demanded - just return the base vector.
6749 if (DemandedElts.extractBits(NumSubElts, InsertIdx) == 0) {
6750 Mask.resize(NumElts);
6751 std::iota(Mask.begin(), Mask.end(), 0);
6752 Ops.push_back(Src);
6753 return true;
6754 }
6755 // Handle CONCAT(SUB0, SUB1).
6756 // Limit to vXi64/splat cases to make the most of cross lane shuffles.
6757 if (Depth > 0 && InsertIdx == NumSubElts && NumElts == (2 * NumSubElts) &&
6758 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6759 Src.getOperand(0).isUndef() &&
6760 Src.getOperand(1).getValueType() == SubVT &&
6761 Src.getConstantOperandVal(2) == 0 &&
6762 (NumBitsPerElt == 64 || Src.getOperand(1) == Sub) &&
6763 SDNode::areOnlyUsersOf({N.getNode(), Src.getNode()}, Sub.getNode())) {
6764 Mask.resize(NumElts);
6765 std::iota(Mask.begin(), Mask.begin() + NumSubElts, 0);
6766 std::iota(Mask.begin() + NumSubElts, Mask.end(), NumElts);
6767 Ops.push_back(Src.getOperand(1));
6768 Ops.push_back(Sub);
6769 return true;
6770 }
6771 // Handle INSERT_SUBVECTOR(UNDEF, SUB, IDX) iff IDX != 0
6772 if (InsertIdx != 0 && Src.isUndef() &&
6774 Mask.assign(NumElts, SM_SentinelUndef);
6775 std::iota(Mask.begin() + InsertIdx, Mask.begin() + InsertIdx + NumSubElts,
6776 0);
6777 Ops.push_back(Sub);
6778 return true;
6779 }
6780 if (!N->isOnlyUserOf(Sub.getNode()))
6781 return false;
6782
6783 SmallVector<int, 64> SubMask;
6784 SmallVector<SDValue, 2> SubInputs;
6786 EVT SubSrcVT = SubSrc.getValueType();
6787 if (!SubSrcVT.isVector())
6788 return false;
6789
6790 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
6791 if (SubSrc.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6792 SubSrc.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6793 uint64_t ExtractIdx = SubSrc.getConstantOperandVal(1);
6794 SDValue SubSrcSrc = SubSrc.getOperand(0);
6795 unsigned NumSubSrcSrcElts =
6796 SubSrcSrc.getValueType().getVectorNumElements();
6797 unsigned MaxElts = std::max(NumElts, NumSubSrcSrcElts);
6798 assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcSrcElts) == 0 &&
6799 "Subvector valuetype mismatch");
6800 InsertIdx *= (MaxElts / NumElts);
6801 ExtractIdx *= (MaxElts / NumSubSrcSrcElts);
6802 NumSubElts *= (MaxElts / NumElts);
6803 bool SrcIsUndef = Src.isUndef();
6804 for (int i = 0; i != (int)MaxElts; ++i)
6805 Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
6806 for (int i = 0; i != (int)NumSubElts; ++i)
6807 Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
6808 if (!SrcIsUndef)
6809 Ops.push_back(Src);
6810 Ops.push_back(SubSrcSrc);
6811 return true;
6812 }
6813
6814 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6815 APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
6816 if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
6817 Depth + 1, ResolveKnownElts))
6818 return false;
6819
6820 // Subvector shuffle inputs must not be larger than the subvector.
6821 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
6822 return SubVT.getFixedSizeInBits() <
6823 SubInput.getValueSizeInBits().getFixedValue();
6824 }))
6825 return false;
6826
6827 if (SubMask.size() != NumSubElts) {
6828 assert(((SubMask.size() % NumSubElts) == 0 ||
6829 (NumSubElts % SubMask.size()) == 0) &&
6830 "Illegal submask scale");
6831 if ((NumSubElts % SubMask.size()) == 0) {
6832 int Scale = NumSubElts / SubMask.size();
6833 SmallVector<int, 64> ScaledSubMask;
6834 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
6835 SubMask = ScaledSubMask;
6836 } else {
6837 int Scale = SubMask.size() / NumSubElts;
6838 NumSubElts = SubMask.size();
6839 NumElts *= Scale;
6840 InsertIdx *= Scale;
6841 }
6842 }
6843 Ops.push_back(Src);
6844 Ops.append(SubInputs.begin(), SubInputs.end());
6845 if (ISD::isBuildVectorAllZeros(Src.getNode()))
6846 Mask.append(NumElts, SM_SentinelZero);
6847 else
6848 for (int i = 0; i != (int)NumElts; ++i)
6849 Mask.push_back(i);
6850 for (int i = 0; i != (int)NumSubElts; ++i) {
6851 int M = SubMask[i];
6852 if (0 <= M) {
6853 int InputIdx = M / NumSubElts;
6854 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6855 }
6856 Mask[i + InsertIdx] = M;
6857 }
6858 return true;
6859 }
6860 case X86ISD::PINSRB:
6861 case X86ISD::PINSRW:
6864 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
6865 // vector, for matching src/dst vector types.
6866 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
6867
6868 unsigned DstIdx = 0;
6869 if (Opcode != ISD::SCALAR_TO_VECTOR) {
6870 // Check we have an in-range constant insertion index.
6871 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6872 N.getConstantOperandAPInt(2).uge(NumElts))
6873 return false;
6874 DstIdx = N.getConstantOperandVal(2);
6875
6876 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
6877 if (X86::isZeroNode(Scl)) {
6878 Ops.push_back(N.getOperand(0));
6879 for (unsigned i = 0; i != NumElts; ++i)
6880 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
6881 return true;
6882 }
6883 }
6884
6885 // Peek through trunc/aext/zext/bitcast.
6886 // TODO: aext shouldn't require SM_SentinelZero padding.
6887 // TODO: handle shift of scalars.
6888 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
6889 while (Scl.getOpcode() == ISD::TRUNCATE ||
6890 Scl.getOpcode() == ISD::ANY_EXTEND ||
6891 Scl.getOpcode() == ISD::ZERO_EXTEND ||
6892 (Scl.getOpcode() == ISD::BITCAST &&
6895 Scl = Scl.getOperand(0);
6896 MinBitsPerElt =
6897 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
6898 }
6899 if ((MinBitsPerElt % 8) != 0)
6900 return false;
6901
6902 // Attempt to find the source vector the scalar was extracted from.
6903 SDValue SrcExtract;
6904 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
6905 Scl.getOpcode() == X86ISD::PEXTRW ||
6906 Scl.getOpcode() == X86ISD::PEXTRB) &&
6907 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6908 SrcExtract = Scl;
6909 }
6910 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6911 return false;
6912
6913 SDValue SrcVec = SrcExtract.getOperand(0);
6914 EVT SrcVT = SrcVec.getValueType();
6915 if (!SrcVT.getScalarType().isByteSized())
6916 return false;
6917 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6918 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
6919 unsigned DstByte = DstIdx * NumBytesPerElt;
6920 MinBitsPerElt =
6921 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
6922
6923 // Create 'identity' byte level shuffle mask and then add inserted bytes.
6924 if (Opcode == ISD::SCALAR_TO_VECTOR) {
6925 Ops.push_back(SrcVec);
6926 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6927 } else {
6928 Ops.push_back(SrcVec);
6929 Ops.push_back(N.getOperand(0));
6930 for (int i = 0; i != (int)NumSizeInBytes; ++i)
6931 Mask.push_back(NumSizeInBytes + i);
6932 }
6933
6934 unsigned MinBytesPerElts = MinBitsPerElt / 8;
6935 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
6936 for (unsigned i = 0; i != MinBytesPerElts; ++i)
6937 Mask[DstByte + i] = SrcByte + i;
6938 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
6939 Mask[DstByte + i] = SM_SentinelZero;
6940 return true;
6941 }
6942 case X86ISD::PACKSS:
6943 case X86ISD::PACKUS: {
6944 SDValue N0 = N.getOperand(0);
6945 SDValue N1 = N.getOperand(1);
6946 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6947 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6948 "Unexpected input value type");
6949
6950 APInt EltsLHS, EltsRHS;
6951 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
6952
6953 // If we know input saturation won't happen (or we don't care for particular
6954 // lanes), we can treat this as a truncation shuffle.
6955 bool Offset0 = false, Offset1 = false;
6956 if (Opcode == X86ISD::PACKSS) {
6957 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6958 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
6959 (!(N1.isUndef() || EltsRHS.isZero()) &&
6960 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
6961 return false;
6962 // We can't easily fold ASHR into a shuffle, but if it was feeding a
6963 // PACKSS then it was likely being used for sign-extension for a
6964 // truncation, so just peek through and adjust the mask accordingly.
6965 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
6966 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
6967 Offset0 = true;
6968 N0 = N0.getOperand(0);
6969 }
6970 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
6971 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
6972 Offset1 = true;
6973 N1 = N1.getOperand(0);
6974 }
6975 } else {
6976 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6977 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6978 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
6979 (!(N1.isUndef() || EltsRHS.isZero()) &&
6980 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
6981 return false;
6982 }
6983
6984 bool IsUnary = (N0 == N1);
6985
6986 Ops.push_back(N0);
6987 if (!IsUnary)
6988 Ops.push_back(N1);
6989
6990 createPackShuffleMask(VT, Mask, IsUnary);
6991
6992 if (Offset0 || Offset1) {
6993 for (int &M : Mask)
6994 if ((Offset0 && isInRange(M, 0, NumElts)) ||
6995 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
6996 ++M;
6997 }
6998 return true;
6999 }
7000 case ISD::VSELECT:
7001 case X86ISD::BLENDV: {
7002 SDValue Cond = N.getOperand(0);
7003 if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
7004 Ops.push_back(N.getOperand(1));
7005 Ops.push_back(N.getOperand(2));
7006 return true;
7007 }
7008 return false;
7009 }
7010 case X86ISD::VTRUNC: {
7011 SDValue Src = N.getOperand(0);
7012 EVT SrcVT = Src.getValueType();
7013 if (SrcVT.getSizeInBits() != NumSizeInBits)
7014 return false;
7015 unsigned NumSrcElts = SrcVT.getVectorNumElements();
7016 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7017 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
7018 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
7019 for (unsigned i = 0; i != NumSrcElts; ++i)
7020 Mask.push_back(i * Scale);
7021 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
7022 Ops.push_back(Src);
7023 return true;
7024 }
7025 case ISD::SHL:
7026 case ISD::SRL: {
7027 APInt UndefElts;
7028 SmallVector<APInt, 32> EltBits;
7029 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7030 UndefElts, EltBits,
7031 /*AllowWholeUndefs*/ true,
7032 /*AllowPartialUndefs*/ false))
7033 return false;
7034
7035 // We can only decode 'whole byte' bit shifts as shuffles.
7036 for (unsigned I = 0; I != NumElts; ++I)
7037 if (DemandedElts[I] && !UndefElts[I] &&
7038 (EltBits[I].urem(8) != 0 || EltBits[I].uge(NumBitsPerElt)))
7039 return false;
7040
7041 Mask.append(NumSizeInBytes, SM_SentinelUndef);
7042 Ops.push_back(N.getOperand(0));
7043
7044 for (unsigned I = 0; I != NumElts; ++I) {
7045 if (!DemandedElts[I] || UndefElts[I])
7046 continue;
7047 unsigned ByteShift = EltBits[I].getZExtValue() / 8;
7048 unsigned Lo = I * NumBytesPerElt;
7049 unsigned Hi = Lo + NumBytesPerElt;
7050 // Clear mask to all zeros and insert the shifted byte indices.
7051 std::fill(Mask.begin() + Lo, Mask.begin() + Hi, SM_SentinelZero);
7052 if (ISD::SHL == Opcode)
7053 std::iota(Mask.begin() + Lo + ByteShift, Mask.begin() + Hi, Lo);
7054 else
7055 std::iota(Mask.begin() + Lo, Mask.begin() + Hi - ByteShift,
7056 Lo + ByteShift);
7057 }
7058 return true;
7059 }
7060 case X86ISD::VSHLI:
7061 case X86ISD::VSRLI: {
7062 uint64_t ShiftVal = N.getConstantOperandVal(1);
7063 // Out of range bit shifts are guaranteed to be zero.
7064 if (NumBitsPerElt <= ShiftVal) {
7065 Mask.append(NumElts, SM_SentinelZero);
7066 return true;
7067 }
7068
7069 // We can only decode 'whole byte' bit shifts as shuffles.
7070 if ((ShiftVal % 8) != 0)
7071 break;
7072
7073 uint64_t ByteShift = ShiftVal / 8;
7074 Ops.push_back(N.getOperand(0));
7075
7076 // Clear mask to all zeros and insert the shifted byte indices.
7077 Mask.append(NumSizeInBytes, SM_SentinelZero);
7078
7079 if (X86ISD::VSHLI == Opcode) {
7080 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7081 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7082 Mask[i + j] = i + j - ByteShift;
7083 } else {
7084 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7085 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7086 Mask[i + j - ByteShift] = i + j;
7087 }
7088 return true;
7089 }
7090 case ISD::ROTL:
7091 case ISD::ROTR: {
7092 APInt UndefElts;
7093 SmallVector<APInt, 32> EltBits;
7094 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7095 UndefElts, EltBits,
7096 /*AllowWholeUndefs*/ true,
7097 /*AllowPartialUndefs*/ false))
7098 return false;
7099
7100 // We can only decode 'whole byte' bit rotates as shuffles.
7101 for (unsigned I = 0; I != NumElts; ++I)
7102 if (DemandedElts[I] && !UndefElts[I] &&
7103 (EltBits[I].urem(NumBitsPerElt) % 8) != 0)
7104 return false;
7105
7106 Ops.push_back(N.getOperand(0));
7107 for (unsigned I = 0; I != NumElts; ++I) {
7108 if (!DemandedElts[I] || UndefElts[I]) {
7109 Mask.append(NumBytesPerElt, SM_SentinelUndef);
7110 continue;
7111 }
7112 int Offset = EltBits[I].urem(NumBitsPerElt) / 8;
7113 Offset = (ISD::ROTL == Opcode ? NumBytesPerElt - Offset : Offset);
7114 int BaseIdx = I * NumBytesPerElt;
7115 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7116 Mask.push_back(BaseIdx + ((Offset + J) % NumBytesPerElt));
7117 }
7118 }
7119 return true;
7120 }
7121 case X86ISD::VROTLI:
7122 case X86ISD::VROTRI: {
7123 // We can only decode 'whole byte' bit rotates as shuffles.
7124 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7125 if ((RotateVal % 8) != 0)
7126 return false;
7127 Ops.push_back(N.getOperand(0));
7128 int Offset = RotateVal / 8;
7129 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7130 for (int i = 0; i != (int)NumElts; ++i) {
7131 int BaseIdx = i * NumBytesPerElt;
7132 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7133 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7134 }
7135 }
7136 return true;
7137 }
7138 case X86ISD::VSHLD:
7139 case X86ISD::VSHRD: {
7140 // We can only decode 'whole byte' bit funnel shifts as shuffles.
7141 uint64_t ShiftVal = N.getConstantOperandAPInt(2).urem(NumBitsPerElt);
7142 int Offset = ShiftVal / 8;
7143 if ((ShiftVal % 8) != 0 || Offset == 0)
7144 return false;
7145 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 1 : 0));
7146 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 0 : 1));
7147 Offset = X86ISD::VSHRD == Opcode ? (NumBytesPerElt - Offset) : Offset;
7148 for (int I = 0; I != (int)NumElts; ++I) {
7149 int BaseIdx = (I * NumBytesPerElt) - Offset;
7150 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7151 int MaskIdx = BaseIdx + J;
7152 MaskIdx += J < Offset ? (NumSizeInBytes + NumBytesPerElt) : 0;
7153 Mask.push_back(MaskIdx);
7154 }
7155 }
7156 return true;
7157 }
7158 case X86ISD::VBROADCAST: {
7159 SDValue Src = N.getOperand(0);
7160 if (!Src.getSimpleValueType().isVector()) {
7161 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7162 !isNullConstant(Src.getOperand(1)) ||
7163 Src.getOperand(0).getValueType().getScalarType() !=
7164 VT.getScalarType())
7165 return false;
7166 Src = Src.getOperand(0);
7167 }
7168 Ops.push_back(Src);
7169 Mask.append(NumElts, 0);
7170 return true;
7171 }
7173 SDValue Src = N.getOperand(0);
7174 EVT SrcVT = Src.getValueType();
7175 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7176
7177 // Extended source must be a simple vector.
7178 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7179 (NumBitsPerSrcElt % 8) != 0)
7180 return false;
7181
7182 // We can only handle all-signbits extensions.
7183 APInt DemandedSrcElts =
7184 DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
7185 if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
7186 return false;
7187
7188 assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
7189 unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
7190 for (unsigned I = 0; I != NumElts; ++I)
7191 Mask.append(Scale, I);
7192 Ops.push_back(Src);
7193 return true;
7194 }
7195 case ISD::ZERO_EXTEND:
7196 case ISD::ANY_EXTEND:
7199 SDValue Src = N.getOperand(0);
7200 EVT SrcVT = Src.getValueType();
7201
7202 // Extended source must be a simple vector.
7203 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7204 (SrcVT.getScalarSizeInBits() % 8) != 0)
7205 return false;
7206
7207 bool IsAnyExtend =
7208 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7209 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7210 IsAnyExtend, Mask);
7211 Ops.push_back(Src);
7212 return true;
7213 }
7214 }
7215
7216 return false;
7217}
7218
7219/// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7221 SmallVectorImpl<int> &Mask) {
7222 int MaskWidth = Mask.size();
7223 SmallVector<SDValue, 16> UsedInputs;
7224 for (int i = 0, e = Inputs.size(); i < e; ++i) {
7225 int lo = UsedInputs.size() * MaskWidth;
7226 int hi = lo + MaskWidth;
7227
7228 // Strip UNDEF input usage.
7229 if (Inputs[i].isUndef())
7230 for (int &M : Mask)
7231 if ((lo <= M) && (M < hi))
7232 M = SM_SentinelUndef;
7233
7234 // Check for unused inputs.
7235 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7236 for (int &M : Mask)
7237 if (lo <= M)
7238 M -= MaskWidth;
7239 continue;
7240 }
7241
7242 // Check for repeated inputs.
7243 bool IsRepeat = false;
7244 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7245 if (peekThroughBitcasts(UsedInputs[j]) != peekThroughBitcasts(Inputs[i]))
7246 continue;
7247 for (int &M : Mask)
7248 if (lo <= M)
7249 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7250 IsRepeat = true;
7251 break;
7252 }
7253 if (IsRepeat)
7254 continue;
7255
7256 UsedInputs.push_back(Inputs[i]);
7257 }
7258 Inputs = std::move(UsedInputs);
7259}
7260
7261/// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7262/// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7263/// Returns true if the target shuffle mask was decoded.
7264static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7267 APInt &KnownUndef, APInt &KnownZero,
7268 const SelectionDAG &DAG, unsigned Depth,
7269 bool ResolveKnownElts) {
7271 return false; // Limit search depth.
7272
7273 EVT VT = Op.getValueType();
7274 if (!VT.isSimple() || !VT.isVector())
7275 return false;
7276
7277 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7278 if (ResolveKnownElts)
7279 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7280 return true;
7281 }
7282 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7283 ResolveKnownElts)) {
7284 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7285 return true;
7286 }
7287 return false;
7288}
7289
7290static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7293 const SelectionDAG &DAG, unsigned Depth,
7294 bool ResolveKnownElts) {
7295 APInt KnownUndef, KnownZero;
7296 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7297 KnownZero, DAG, Depth, ResolveKnownElts);
7298}
7299
7302 const SelectionDAG &DAG, unsigned Depth = 0,
7303 bool ResolveKnownElts = true) {
7304 EVT VT = Op.getValueType();
7305 if (!VT.isSimple() || !VT.isVector())
7306 return false;
7307
7308 unsigned NumElts = Op.getValueType().getVectorNumElements();
7309 APInt DemandedElts = APInt::getAllOnes(NumElts);
7310 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
7311 ResolveKnownElts);
7312}
7313
7314// Attempt to create a scalar/subvector broadcast from the base MemSDNode.
7315static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
7316 EVT MemVT, MemSDNode *Mem, unsigned Offset,
7317 SelectionDAG &DAG) {
7318 assert((Opcode == X86ISD::VBROADCAST_LOAD ||
7319 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
7320 "Unknown broadcast load type");
7321
7322 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
7323 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
7324 return SDValue();
7325
7326 SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
7328 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7329 SDValue Ops[] = {Mem->getChain(), Ptr};
7330 SDValue BcstLd = DAG.getMemIntrinsicNode(
7331 Opcode, DL, Tys, Ops, MemVT,
7333 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
7334 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
7335 return BcstLd;
7336}
7337
7338/// Returns the scalar element that will make up the i'th
7339/// element of the result of the vector shuffle.
7340static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7341 SelectionDAG &DAG, unsigned Depth) {
7343 return SDValue(); // Limit search depth.
7344
7345 EVT VT = Op.getValueType();
7346 unsigned Opcode = Op.getOpcode();
7347 unsigned NumElems = VT.getVectorNumElements();
7348
7349 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7350 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7351 int Elt = SV->getMaskElt(Index);
7352
7353 if (Elt < 0)
7354 return DAG.getUNDEF(VT.getVectorElementType());
7355
7356 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7357 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7358 }
7359
7360 // Recurse into target specific vector shuffles to find scalars.
7361 if (isTargetShuffle(Opcode)) {
7362 MVT ShufVT = VT.getSimpleVT();
7363 MVT ShufSVT = ShufVT.getVectorElementType();
7364 int NumElems = (int)ShufVT.getVectorNumElements();
7365 SmallVector<int, 16> ShuffleMask;
7367 if (!getTargetShuffleMask(Op, true, ShuffleOps, ShuffleMask))
7368 return SDValue();
7369
7370 int Elt = ShuffleMask[Index];
7371 if (Elt == SM_SentinelZero)
7372 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7373 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7374 if (Elt == SM_SentinelUndef)
7375 return DAG.getUNDEF(ShufSVT);
7376
7377 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7378 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7379 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7380 }
7381
7382 // Recurse into insert_subvector base/sub vector to find scalars.
7383 if (Opcode == ISD::INSERT_SUBVECTOR) {
7384 SDValue Vec = Op.getOperand(0);
7385 SDValue Sub = Op.getOperand(1);
7386 uint64_t SubIdx = Op.getConstantOperandVal(2);
7387 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7388
7389 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7390 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7391 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7392 }
7393
7394 // Recurse into concat_vectors sub vector to find scalars.
7395 if (Opcode == ISD::CONCAT_VECTORS) {
7396 EVT SubVT = Op.getOperand(0).getValueType();
7397 unsigned NumSubElts = SubVT.getVectorNumElements();
7398 uint64_t SubIdx = Index / NumSubElts;
7399 uint64_t SubElt = Index % NumSubElts;
7400 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
7401 }
7402
7403 // Recurse into extract_subvector src vector to find scalars.
7404 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
7405 SDValue Src = Op.getOperand(0);
7406 uint64_t SrcIdx = Op.getConstantOperandVal(1);
7407 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
7408 }
7409
7410 // We only peek through bitcasts of the same vector width.
7411 if (Opcode == ISD::BITCAST) {
7412 SDValue Src = Op.getOperand(0);
7413 EVT SrcVT = Src.getValueType();
7414 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
7415 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
7416 return SDValue();
7417 }
7418
7419 // Actual nodes that may contain scalar elements
7420
7421 // For insert_vector_elt - either return the index matching scalar or recurse
7422 // into the base vector.
7423 if (Opcode == ISD::INSERT_VECTOR_ELT &&
7424 isa<ConstantSDNode>(Op.getOperand(2))) {
7425 if (Op.getConstantOperandAPInt(2) == Index)
7426 return Op.getOperand(1);
7427 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
7428 }
7429
7430 if (Opcode == ISD::SCALAR_TO_VECTOR)
7431 return (Index == 0) ? Op.getOperand(0)
7432 : DAG.getUNDEF(VT.getVectorElementType());
7433
7434 if (Opcode == ISD::BUILD_VECTOR)
7435 return Op.getOperand(Index);
7436
7437 return SDValue();
7438}
7439
7440// Use PINSRB/PINSRW/PINSRD to create a build vector.
7442 const APInt &NonZeroMask,
7443 unsigned NumNonZero, unsigned NumZero,
7444 SelectionDAG &DAG,
7445 const X86Subtarget &Subtarget) {
7446 MVT VT = Op.getSimpleValueType();
7447 unsigned NumElts = VT.getVectorNumElements();
7448 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7449 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7450 "Illegal vector insertion");
7451
7452 SDValue V;
7453 bool First = true;
7454
7455 for (unsigned i = 0; i < NumElts; ++i) {
7456 bool IsNonZero = NonZeroMask[i];
7457 if (!IsNonZero)
7458 continue;
7459
7460 // If the build vector contains zeros or our first insertion is not the
7461 // first index then insert into zero vector to break any register
7462 // dependency else use SCALAR_TO_VECTOR.
7463 if (First) {
7464 First = false;
7465 if (NumZero || 0 != i)
7466 V = getZeroVector(VT, Subtarget, DAG, DL);
7467 else {
7468 assert(0 == i && "Expected insertion into zero-index");
7469 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7470 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7471 V = DAG.getBitcast(VT, V);
7472 continue;
7473 }
7474 }
7475 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, V, Op.getOperand(i),
7476 DAG.getVectorIdxConstant(i, DL));
7477 }
7478
7479 return V;
7480}
7481
7482/// Custom lower build_vector of v16i8.
7484 const APInt &NonZeroMask,
7485 unsigned NumNonZero, unsigned NumZero,
7486 SelectionDAG &DAG,
7487 const X86Subtarget &Subtarget) {
7488 if (NumNonZero > 8 && !Subtarget.hasSSE41())
7489 return SDValue();
7490
7491 // SSE4.1 - use PINSRB to insert each byte directly.
7492 if (Subtarget.hasSSE41())
7493 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero,
7494 DAG, Subtarget);
7495
7496 SDValue V;
7497
7498 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7499 // If both the lowest 16-bits are non-zero, then convert to MOVD.
7500 if (!NonZeroMask.extractBits(2, 0).isZero() &&
7501 !NonZeroMask.extractBits(2, 2).isZero()) {
7502 for (unsigned I = 0; I != 4; ++I) {
7503 if (!NonZeroMask[I])
7504 continue;
7505 SDValue Elt = DAG.getZExtOrTrunc(Op.getOperand(I), DL, MVT::i32);
7506 if (I != 0)
7507 Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt,
7508 DAG.getConstant(I * 8, DL, MVT::i8));
7509 V = V ? DAG.getNode(ISD::OR, DL, MVT::i32, V, Elt) : Elt;
7510 }
7511 assert(V && "Failed to fold v16i8 vector to zero");
7512 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7513 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32, V);
7514 V = DAG.getBitcast(MVT::v8i16, V);
7515 }
7516 for (unsigned i = V ? 4 : 0; i < 16; i += 2) {
7517 bool ThisIsNonZero = NonZeroMask[i];
7518 bool NextIsNonZero = NonZeroMask[i + 1];
7519 if (!ThisIsNonZero && !NextIsNonZero)
7520 continue;
7521
7522 SDValue Elt;
7523 if (ThisIsNonZero) {
7524 if (NumZero || NextIsNonZero)
7525 Elt = DAG.getZExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7526 else
7527 Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7528 }
7529
7530 if (NextIsNonZero) {
7531 SDValue NextElt = Op.getOperand(i + 1);
7532 if (i == 0 && NumZero)
7533 NextElt = DAG.getZExtOrTrunc(NextElt, DL, MVT::i32);
7534 else
7535 NextElt = DAG.getAnyExtOrTrunc(NextElt, DL, MVT::i32);
7536 NextElt = DAG.getNode(ISD::SHL, DL, MVT::i32, NextElt,
7537 DAG.getConstant(8, DL, MVT::i8));
7538 if (ThisIsNonZero)
7539 Elt = DAG.getNode(ISD::OR, DL, MVT::i32, NextElt, Elt);
7540 else
7541 Elt = NextElt;
7542 }
7543
7544 // If our first insertion is not the first index or zeros are needed, then
7545 // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
7546 // elements undefined).
7547 if (!V) {
7548 if (i != 0 || NumZero)
7549 V = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7550 else {
7551 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, Elt);
7552 V = DAG.getBitcast(MVT::v8i16, V);
7553 continue;
7554 }
7555 }
7556 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
7557 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16, V, Elt,
7558 DAG.getVectorIdxConstant(i / 2, DL));
7559 }
7560
7561 return DAG.getBitcast(MVT::v16i8, V);
7562}
7563
7564/// Custom lower build_vector of v8i16.
7566 const APInt &NonZeroMask,
7567 unsigned NumNonZero, unsigned NumZero,
7568 SelectionDAG &DAG,
7569 const X86Subtarget &Subtarget) {
7570 if (NumNonZero > 4 && !Subtarget.hasSSE41())
7571 return SDValue();
7572
7573 // Use PINSRW to insert each byte directly.
7574 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero, DAG,
7575 Subtarget);
7576}
7577
7578/// Custom lower build_vector of v4i32 or v4f32.
7580 SelectionDAG &DAG,
7581 const X86Subtarget &Subtarget) {
7582 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
7583 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
7584 // Because we're creating a less complicated build vector here, we may enable
7585 // further folding of the MOVDDUP via shuffle transforms.
7586 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
7587 Op.getOperand(0) == Op.getOperand(2) &&
7588 Op.getOperand(1) == Op.getOperand(3) &&
7589 Op.getOperand(0) != Op.getOperand(1)) {
7590 MVT VT = Op.getSimpleValueType();
7591 MVT EltVT = VT.getVectorElementType();
7592 // Create a new build vector with the first 2 elements followed by undef
7593 // padding, bitcast to v2f64, duplicate, and bitcast back.
7594 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
7595 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
7596 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7597 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7598 return DAG.getBitcast(VT, Dup);
7599 }
7600
7601 // Find all zeroable elements.
7602 std::bitset<4> Zeroable, Undefs;
7603 for (int i = 0; i < 4; ++i) {
7604 SDValue Elt = Op.getOperand(i);
7605 Undefs[i] = Elt.isUndef();
7606 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7607 }
7608 assert(Zeroable.size() - Zeroable.count() > 1 &&
7609 "We expect at least two non-zero elements!");
7610
7611 // We only know how to deal with build_vector nodes where elements are either
7612 // zeroable or extract_vector_elt with constant index.
7613 SDValue FirstNonZero;
7614 unsigned FirstNonZeroIdx;
7615 for (unsigned i = 0; i < 4; ++i) {
7616 if (Zeroable[i])
7617 continue;
7618 SDValue Elt = Op.getOperand(i);
7619 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7621 return SDValue();
7622 // Make sure that this node is extracting from a 128-bit vector.
7623 MVT VT = Elt.getOperand(0).getSimpleValueType();
7624 if (!VT.is128BitVector())
7625 return SDValue();
7626 if (!FirstNonZero.getNode()) {
7627 FirstNonZero = Elt;
7628 FirstNonZeroIdx = i;
7629 }
7630 }
7631
7632 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
7633 SDValue V1 = FirstNonZero.getOperand(0);
7634 MVT VT = V1.getSimpleValueType();
7635
7636 // See if this build_vector can be lowered as a blend with zero.
7637 SDValue Elt;
7638 unsigned EltMaskIdx, EltIdx;
7639 int Mask[4];
7640 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7641 if (Zeroable[EltIdx]) {
7642 // The zero vector will be on the right hand side.
7643 Mask[EltIdx] = EltIdx+4;
7644 continue;
7645 }
7646
7647 Elt = Op->getOperand(EltIdx);
7648 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7649 EltMaskIdx = Elt.getConstantOperandVal(1);
7650 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7651 break;
7652 Mask[EltIdx] = EltIdx;
7653 }
7654
7655 if (EltIdx == 4) {
7656 // Let the shuffle legalizer deal with blend operations.
7657 SDValue VZeroOrUndef = (Zeroable == Undefs)
7658 ? DAG.getUNDEF(VT)
7659 : getZeroVector(VT, Subtarget, DAG, DL);
7660 if (V1.getSimpleValueType() != VT)
7661 V1 = DAG.getBitcast(VT, V1);
7662 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
7663 }
7664
7665 // See if we can lower this build_vector to a INSERTPS.
7666 if (!Subtarget.hasSSE41())
7667 return SDValue();
7668
7669 SDValue V2 = Elt.getOperand(0);
7670 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7671 V1 = SDValue();
7672
7673 bool CanFold = true;
7674 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7675 if (Zeroable[i])
7676 continue;
7677
7678 SDValue Current = Op->getOperand(i);
7679 SDValue SrcVector = Current->getOperand(0);
7680 if (!V1.getNode())
7681 V1 = SrcVector;
7682 CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
7683 }
7684
7685 if (!CanFold)
7686 return SDValue();
7687
7688 assert(V1.getNode() && "Expected at least two non-zero elements!");
7689 if (V1.getSimpleValueType() != MVT::v4f32)
7690 V1 = DAG.getBitcast(MVT::v4f32, V1);
7691 if (V2.getSimpleValueType() != MVT::v4f32)
7692 V2 = DAG.getBitcast(MVT::v4f32, V2);
7693
7694 // Ok, we can emit an INSERTPS instruction.
7695 unsigned ZMask = Zeroable.to_ulong();
7696
7697 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7698 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7699 SDValue Result =
7700 DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7701 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
7702 return DAG.getBitcast(VT, Result);
7703}
7704
7705/// Return a vector logical shift node.
7706static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7707 SelectionDAG &DAG, const TargetLowering &TLI,
7708 const SDLoc &dl) {
7709 assert(VT.is128BitVector() && "Unknown type for VShift");
7710 MVT ShVT = MVT::v16i8;
7711 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7712 SrcOp = DAG.getBitcast(ShVT, SrcOp);
7713 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
7714 SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
7715 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7716}
7717
7719 SelectionDAG &DAG) {
7720
7721 // Check if the scalar load can be widened into a vector load. And if
7722 // the address is "base + cst" see if the cst can be "absorbed" into
7723 // the shuffle mask.
7725 SDValue Ptr = LD->getBasePtr();
7726 if (!ISD::isNormalLoad(LD) || !LD->isSimple())
7727 return SDValue();
7728 EVT PVT = LD->getValueType(0);
7729 if (PVT != MVT::i32 && PVT != MVT::f32)
7730 return SDValue();
7731
7732 int FI = -1;
7733 int64_t Offset = 0;
7734 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7735 FI = FINode->getIndex();
7736 Offset = 0;
7737 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7739 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7741 Ptr = Ptr.getOperand(0);
7742 } else {
7743 return SDValue();
7744 }
7745
7746 // FIXME: 256-bit vector instructions don't require a strict alignment,
7747 // improve this code to support it better.
7748 Align RequiredAlign(VT.getSizeInBits() / 8);
7749 SDValue Chain = LD->getChain();
7750 // Make sure the stack object alignment is at least 16 or 32.
7752 MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
7753 if (!InferredAlign || *InferredAlign < RequiredAlign) {
7754 if (MFI.isFixedObjectIndex(FI)) {
7755 // Can't change the alignment. FIXME: It's possible to compute
7756 // the exact stack offset and reference FI + adjust offset instead.
7757 // If someone *really* cares about this. That's the way to implement it.
7758 return SDValue();
7759 } else {
7760 MFI.setObjectAlignment(FI, RequiredAlign);
7761 }
7762 }
7763
7764 // (Offset % 16 or 32) must be multiple of 4. Then address is then
7765 // Ptr + (Offset & ~15).
7766 if (Offset < 0)
7767 return SDValue();
7768 if ((Offset % RequiredAlign.value()) & 3)
7769 return SDValue();
7770 int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
7771 if (StartOffset) {
7772 SDLoc DL(Ptr);
7773 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7774 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7775 }
7776
7777 int EltNo = (Offset - StartOffset) >> 2;
7778 unsigned NumElems = VT.getVectorNumElements();
7779
7780 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
7781 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
7782 LD->getPointerInfo().getWithOffset(StartOffset));
7783
7784 SmallVector<int, 8> Mask(NumElems, EltNo);
7785
7786 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
7787 }
7788
7789 return SDValue();
7790}
7791
7792// Recurse to find a LoadSDNode source and the accumulated ByteOffest.
7793static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
7794 if (ISD::isNON_EXTLoad(Elt.getNode())) {
7795 auto *BaseLd = cast<LoadSDNode>(Elt);
7796 if (!BaseLd->isSimple())
7797 return false;
7798 Ld = BaseLd;
7799 ByteOffset = 0;
7800 return true;
7801 }
7802
7803 switch (Elt.getOpcode()) {
7804 case ISD::BITCAST:
7805 case ISD::TRUNCATE:
7807 return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
7808 case ISD::SRL:
7809 if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7810 uint64_t Amt = AmtC->getZExtValue();
7811 if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
7812 ByteOffset += Amt / 8;
7813 return true;
7814 }
7815 }
7816 break;
7818 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7819 SDValue Src = Elt.getOperand(0);
7820 unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
7821 unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
7822 if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
7823 findEltLoadSrc(Src, Ld, ByteOffset)) {
7824 uint64_t Idx = IdxC->getZExtValue();
7825 ByteOffset += Idx * (SrcSizeInBits / 8);
7826 return true;
7827 }
7828 }
7829 break;
7830 }
7831
7832 return false;
7833}
7834
7835/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7836/// elements can be replaced by a single large load which has the same value as
7837/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7838///
7839/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
7841 const SDLoc &DL, SelectionDAG &DAG,
7842 const X86Subtarget &Subtarget,
7843 bool IsAfterLegalize,
7844 unsigned Depth = 0) {
7846 return SDValue(); // Limit search depth.
7847 if ((VT.getScalarSizeInBits() % 8) != 0)
7848 return SDValue();
7849
7850 // If all of these are oneuse frozen loads, then attempt to create a frozen
7851 // consecutive load.
7852 if (all_of(Elts, [](SDValue Elt) {
7853 return Elt.getOpcode() == ISD::FREEZE &&
7855 Elt.hasOneUse();
7856 })) {
7858 for (SDValue Elt : Elts)
7859 SrcElts.push_back(peekThroughFreeze(Elt));
7860 if (SDValue LD = EltsFromConsecutiveLoads(VT, SrcElts, DL, DAG, Subtarget,
7861 IsAfterLegalize, Depth + 1))
7862 return DAG.getFreeze(LD);
7863 return SDValue();
7864 }
7865
7866 unsigned NumElems = Elts.size();
7867
7868 int LastLoadedElt = -1;
7869 APInt LoadMask = APInt::getZero(NumElems);
7870 APInt ZeroMask = APInt::getZero(NumElems);
7871 APInt UndefMask = APInt::getZero(NumElems);
7872
7873 SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
7874 SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
7875
7876 // For each element in the initializer, see if we've found a load, zero or an
7877 // undef.
7878 for (unsigned i = 0; i < NumElems; ++i) {
7879 SDValue Elt = peekThroughBitcasts(Elts[i]);
7880 if (!Elt.getNode())
7881 return SDValue();
7882 if (Elt.isUndef()) {
7883 UndefMask.setBit(i);
7884 continue;
7885 }
7887 ZeroMask.setBit(i);
7888 continue;
7889 }
7890
7891 // Each loaded element must be the correct fractional portion of the
7892 // requested vector load.
7893 unsigned EltSizeInBits = Elt.getValueSizeInBits();
7894 if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
7895 return SDValue();
7896
7897 if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
7898 return SDValue();
7899 unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
7900 if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
7901 return SDValue();
7902
7903 LoadMask.setBit(i);
7904 LastLoadedElt = i;
7905 }
7906 assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
7907 NumElems &&
7908 "Incomplete element masks");
7909
7910 // Handle Special Cases - all undef or undef/zero.
7911 if (UndefMask.popcount() == NumElems)
7912 return DAG.getUNDEF(VT);
7913 if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
7914 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7915 : DAG.getConstantFP(0.0, DL, VT);
7916
7917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7918 int FirstLoadedElt = LoadMask.countr_zero();
7919 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7920 EVT EltBaseVT = EltBase.getValueType();
7921 assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
7922 "Register/Memory size mismatch");
7923 LoadSDNode *LDBase = Loads[FirstLoadedElt];
7924 assert(LDBase && "Did not find base load for merging consecutive loads");
7925 unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
7926 unsigned BaseSizeInBytes = BaseSizeInBits / 8;
7927 int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
7928 int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
7929 assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
7930
7931 // TODO: Support offsetting the base load.
7932 if (ByteOffsets[FirstLoadedElt] != 0)
7933 return SDValue();
7934
7935 // Check to see if the element's load is consecutive to the base load
7936 // or offset from a previous (already checked) load.
7937 auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
7938 LoadSDNode *Ld = Loads[EltIdx];
7939 int64_t ByteOffset = ByteOffsets[EltIdx];
7940 if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
7941 int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
7942 return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
7943 Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
7944 }
7945 int Stride = EltIdx - FirstLoadedElt;
7946 if (DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes, Stride))
7947 return true;
7948 // Try again using the memory load size (we might have broken a large load
7949 // into smaller elements), ensure the stride is the full memory load size
7950 // apart and a whole number of elements fit in each memory load.
7951 unsigned BaseMemSizeInBits = Base->getMemoryVT().getSizeInBits();
7952 if (((Stride * BaseSizeInBits) % BaseMemSizeInBits) == 0 &&
7953 (BaseMemSizeInBits % BaseSizeInBits) == 0) {
7954 unsigned Scale = BaseMemSizeInBits / BaseSizeInBits;
7955 return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseMemSizeInBits / 8,
7956 Stride / Scale);
7957 }
7958 return false;
7959 };
7960
7961 // Consecutive loads can contain UNDEFS but not ZERO elements.
7962 // Consecutive loads with UNDEFs and ZEROs elements require a
7963 // an additional shuffle stage to clear the ZERO elements.
7964 bool IsConsecutiveLoad = true;
7965 bool IsConsecutiveLoadWithZeros = true;
7966 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7967 if (LoadMask[i]) {
7968 if (!CheckConsecutiveLoad(LDBase, i)) {
7969 IsConsecutiveLoad = false;
7970 IsConsecutiveLoadWithZeros = false;
7971 break;
7972 }
7973 } else if (ZeroMask[i]) {
7974 IsConsecutiveLoad = false;
7975 }
7976 }
7977
7978 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7979 auto MMOFlags = LDBase->getMemOperand()->getFlags();
7980 assert(LDBase->isSimple() &&
7981 "Cannot merge volatile or atomic loads.");
7982 SDValue NewLd =
7983 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7984 LDBase->getPointerInfo(), LDBase->getBaseAlign(), MMOFlags);
7985 for (auto *LD : Loads)
7986 if (LD)
7987 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
7988 return NewLd;
7989 };
7990
7991 // Check if the base load is entirely dereferenceable.
7992 bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
7993 VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
7994
7995 // LOAD - all consecutive load/undefs (must start/end with a load or be
7996 // entirely dereferenceable). If we have found an entire vector of loads and
7997 // undefs, then return a large load of the entire vector width starting at the
7998 // base pointer. If the vector contains zeros, then attempt to shuffle those
7999 // elements.
8000 if (FirstLoadedElt == 0 &&
8001 (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
8002 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8003 if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8004 return SDValue();
8005
8006 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8007 // will lower to regular temporal loads and use the cache.
8008 if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
8009 VT.is256BitVector() && !Subtarget.hasInt256())
8010 return SDValue();
8011
8012 if (NumElems == 1)
8013 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8014
8015 if (!ZeroMask)
8016 return CreateLoad(VT, LDBase);
8017
8018 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8019 // vector and a zero vector to clear out the zero elements.
8020 if (!IsAfterLegalize && VT.isVector()) {
8021 unsigned NumMaskElts = VT.getVectorNumElements();
8022 if ((NumMaskElts % NumElems) == 0) {
8023 unsigned Scale = NumMaskElts / NumElems;
8024 SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8025 for (unsigned i = 0; i < NumElems; ++i) {
8026 if (UndefMask[i])
8027 continue;
8028 int Offset = ZeroMask[i] ? NumMaskElts : 0;
8029 for (unsigned j = 0; j != Scale; ++j)
8030 ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8031 }
8032 SDValue V = CreateLoad(VT, LDBase);
8033 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8034 : DAG.getConstantFP(0.0, DL, VT);
8035 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8036 }
8037 }
8038 }
8039
8040 // If the upper half of a ymm/zmm load is undef then just load the lower half.
8041 if (VT.is256BitVector() || VT.is512BitVector()) {
8042 unsigned HalfNumElems = NumElems / 2;
8043 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
8044 EVT HalfVT =
8045 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8046 SDValue HalfLD =
8047 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8048 DAG, Subtarget, IsAfterLegalize, Depth + 1);
8049 if (HalfLD)
8050 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8051 HalfLD, DAG.getVectorIdxConstant(0, DL));
8052 }
8053 }
8054
8055 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8056 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8057 ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
8058 LoadSizeInBits == 64) &&
8059 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8060 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8061 : MVT::getIntegerVT(LoadSizeInBits);
8062 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8063 // Allow v4f32 on SSE1 only targets.
8064 // FIXME: Add more isel patterns so we can just use VT directly.
8065 if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8066 VecVT = MVT::v4f32;
8067 if (TLI.isTypeLegal(VecVT)) {
8068 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8069 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8070 SDValue ResNode = DAG.getMemIntrinsicNode(
8071 X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8073 for (auto *LD : Loads)
8074 if (LD)
8075 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8076 return DAG.getBitcast(VT, ResNode);
8077 }
8078 }
8079
8080 // BROADCAST - match the smallest possible repetition pattern, load that
8081 // scalar/subvector element and then broadcast to the entire vector.
8082 if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8083 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8084 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8085 unsigned RepeatSize = SubElems * BaseSizeInBits;
8086 unsigned ScalarSize = std::min(RepeatSize, 64u);
8087 if (!Subtarget.hasAVX2() && ScalarSize < 32)
8088 continue;
8089
8090 // Don't attempt a 1:N subvector broadcast - it should be caught by
8091 // combineConcatVectorOps, else will cause infinite loops.
8092 if (RepeatSize > ScalarSize && SubElems == 1)
8093 continue;
8094
8095 bool Match = true;
8096 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8097 for (unsigned i = 0; i != NumElems && Match; ++i) {
8098 if (!LoadMask[i])
8099 continue;
8100 SDValue Elt = peekThroughBitcasts(Elts[i]);
8101 if (RepeatedLoads[i % SubElems].isUndef())
8102 RepeatedLoads[i % SubElems] = Elt;
8103 else
8104 Match &= (RepeatedLoads[i % SubElems] == Elt);
8105 }
8106
8107 // We must have loads at both ends of the repetition.
8108 Match &= !RepeatedLoads.front().isUndef();
8109 Match &= !RepeatedLoads.back().isUndef();
8110 if (!Match)
8111 continue;
8112
8113 EVT RepeatVT =
8114 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8115 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8116 : EVT::getFloatingPointVT(ScalarSize);
8117 if (RepeatSize > ScalarSize)
8118 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8119 RepeatSize / ScalarSize);
8120 EVT BroadcastVT =
8121 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8122 VT.getSizeInBits() / ScalarSize);
8123 if (TLI.isTypeLegal(BroadcastVT)) {
8124 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8125 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize,
8126 Depth + 1)) {
8127 SDValue Broadcast = RepeatLoad;
8128 if (RepeatSize > ScalarSize) {
8129 while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
8130 Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
8131 } else {
8132 if (!Subtarget.hasAVX2() &&
8134 RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
8135 Subtarget,
8136 /*AssumeSingleUse=*/true))
8137 return SDValue();
8138 Broadcast =
8139 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
8140 }
8141 return DAG.getBitcast(VT, Broadcast);
8142 }
8143 }
8144 }
8145 }
8146
8147 // STRIDED - element loads at a uniform byte stride larger than the element
8148 // size are folded into wide load(s) + vector truncation.
8149 // Depth 1 lets the REVERSE block below recurse into us to catch reverse
8150 // strides.
8151 if (Depth <= 1 && Subtarget.hasAVX2() && !IsConsecutiveLoad &&
8152 LoadMask.isAllOnes() && isPowerOf2_32(NumElems) && BaseSizeInBits <= 32 &&
8153 VT.getSizeInBits() >= 128) {
8154 unsigned WideEltBits = 0;
8155 for (unsigned Trial : {16u, 32u, 64u}) {
8156 if (Trial <= BaseSizeInBits || Trial % BaseSizeInBits != 0)
8157 continue;
8158 unsigned LaneStride = Trial / BaseSizeInBits;
8159 bool AllMatch = true;
8160 for (unsigned K = 1; K < NumElems && AllMatch; ++K) {
8161 AllMatch = AllMatch && ByteOffsets[K] == 0 &&
8163 Loads[K], LDBase, BaseSizeInBytes, K * LaneStride);
8164 }
8165 if (AllMatch) {
8166 WideEltBits = Trial;
8167 break;
8168 }
8169 }
8170 if (WideEltBits != 0) {
8171 MVT WideEltVT = MVT::getIntegerVT(WideEltBits);
8172 MVT SrcEltVT = MVT::getIntegerVT(BaseSizeInBits);
8173 // The wide loads read (stride - element) bytes past the last element.
8174 // A stride-aligned base keeps every stride block inside a page that an
8175 // accessed element touches.
8176 unsigned StrideBytes = WideEltBits / 8;
8177 bool RangeSafe =
8178 LDBase->getBaseAlign() >= Align(StrideBytes) ||
8180 NumElems * StrideBytes, *DAG.getContext(), DAG.getDataLayout());
8181 for (unsigned WideRegBits : {512u, 256u, 128u}) {
8182 unsigned LanesPerWideLoad = WideRegBits / WideEltBits;
8183 if (LanesPerWideLoad < 2 || NumElems % LanesPerWideLoad != 0)
8184 continue;
8185 // Truncate to a legal piece at least 128-bit and no narrower
8186 // than the source element.
8187 unsigned PieceEltBits =
8188 std::max(BaseSizeInBits, 128 / LanesPerWideLoad);
8189 MVT PieceEltVT = MVT::getIntegerVT(PieceEltBits);
8190 MVT WideVT = MVT::getVectorVT(WideEltVT, LanesPerWideLoad);
8191 MVT PieceVT = MVT::getVectorVT(PieceEltVT, LanesPerWideLoad);
8192 MVT TruncVT = MVT::getVectorVT(SrcEltVT, NumElems);
8193 MVT ConcatVT = MVT::getVectorVT(PieceEltVT, NumElems);
8194 if (!TLI.isTypeLegal(WideVT) || !TLI.isTypeLegal(PieceVT) ||
8195 !TLI.isTypeLegal(ConcatVT) || !TLI.isTypeLegal(TruncVT))
8196 continue;
8197 unsigned NumWideLoads = NumElems / LanesPerWideLoad;
8198 unsigned BytesPerWideLoad = WideRegBits / 8;
8199 // Without a provable range the last load is shifted back to end at
8200 // the last element. It overlaps the previous load so two are needed.
8201 bool CanShift = NumWideLoads >= 2;
8202 if (!RangeSafe && !CanShift)
8203 continue;
8204 unsigned TailBits = WideEltBits - BaseSizeInBits;
8205 auto MMOFlags = LDBase->getMemOperand()->getFlags();
8206 SDValue BasePtr = LDBase->getBasePtr();
8208 for (unsigned K = 0; K != NumWideLoads; ++K) {
8209 bool ShiftLast = !RangeSafe && K == NumWideLoads - 1;
8210 unsigned Offset = K * BytesPerWideLoad;
8211 if (ShiftLast)
8212 Offset -= TailBits / 8;
8213 SDValue Ptr =
8215 Align LdAlign = commonAlignment(LDBase->getBaseAlign(), Offset);
8216 SDValue Ld =
8217 DAG.getLoad(WideVT, DL, LDBase->getChain(), Ptr,
8219 LdAlign, MMOFlags);
8220 for (auto *LD : Loads)
8221 if (LD)
8222 DAG.makeEquivalentMemoryOrdering(LD, Ld);
8223 // The shifted load leaves each element in its lane's high bits.
8224 if (ShiftLast)
8225 Ld = DAG.getNode(ISD::SRL, DL, WideVT, Ld,
8226 DAG.getShiftAmountConstant(TailBits, WideVT, DL));
8227 Pieces.push_back(DAG.getNode(ISD::TRUNCATE, DL, PieceVT, Ld));
8228 }
8229 SDValue Result = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, Pieces);
8230 Result = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Result);
8231 return DAG.getBitcast(VT, Result);
8232 }
8233 }
8234 }
8235
8236 // REVERSE - attempt to match the loads in reverse and then shuffle back.
8237 // TODO: Do this for any permute or mismatching element counts.
8238 if (Depth == 0 && ZeroMask.isZero() && UndefMask.isZero() &&
8239 TLI.isTypeLegal(VT) && VT.isVector() &&
8240 NumElems == VT.getVectorNumElements()) {
8241 SmallVector<SDValue, 16> ReverseElts(Elts.rbegin(), Elts.rend());
8243 VT, ReverseElts, DL, DAG, Subtarget, IsAfterLegalize, Depth + 1)) {
8244 SmallVector<int, 16> ReverseMask(NumElems);
8245 std::iota(ReverseMask.rbegin(), ReverseMask.rend(), 0);
8246 return DAG.getVectorShuffle(VT, DL, RevLd, DAG.getUNDEF(VT), ReverseMask);
8247 }
8248 }
8249
8250 return SDValue();
8251}
8252
8253// Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8254// load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8255// are consecutive, non-overlapping, and in the right order.
8257 SelectionDAG &DAG,
8258 const X86Subtarget &Subtarget,
8259 bool IsAfterLegalize) {
8261 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8262 if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8263 Elts.push_back(Elt);
8264 continue;
8265 }
8266 return SDValue();
8267 }
8268 assert(Elts.size() == VT.getVectorNumElements());
8269 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8270 IsAfterLegalize);
8271}
8272
8274 const APInt &Undefs, LLVMContext &C) {
8275 unsigned ScalarSize = VT.getScalarSizeInBits();
8276 Type *Ty = EVT(VT.getScalarType()).getTypeForEVT(C);
8277
8278 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8279 if (VT.isFloatingPoint()) {
8280 if (ScalarSize == 16)
8281 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8282 if (ScalarSize == 32)
8283 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8284 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8285 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8286 }
8287 return Constant::getIntegerValue(Ty, Val);
8288 };
8289
8290 SmallVector<Constant *, 32> ConstantVec;
8291 for (unsigned I = 0, E = Bits.size(); I != E; ++I)
8292 ConstantVec.push_back(Undefs[I] ? UndefValue::get(Ty)
8293 : getConstantScalar(Bits[I]));
8294
8295 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8296}
8297
8298static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8299 unsigned SplatBitSize, LLVMContext &C) {
8300 unsigned ScalarSize = VT.getScalarSizeInBits();
8301
8302 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8303 if (VT.isFloatingPoint()) {
8304 if (ScalarSize == 16)
8305 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8306 if (ScalarSize == 32)
8307 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8308 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8309 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8310 }
8311 return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8312 };
8313
8314 if (ScalarSize == SplatBitSize)
8315 return getConstantScalar(SplatValue);
8316
8317 unsigned NumElm = SplatBitSize / ScalarSize;
8318 SmallVector<Constant *, 32> ConstantVec;
8319 for (unsigned I = 0; I != NumElm; ++I) {
8320 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
8321 ConstantVec.push_back(getConstantScalar(Val));
8322 }
8323 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8324}
8325
8327 for (auto *U : N->users()) {
8328 unsigned Opc = U->getOpcode();
8329 // VPERMV/VPERMV3 shuffles can never fold their index operands.
8330 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8331 return false;
8332 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8333 return false;
8334 if (isTargetShuffle(Opc))
8335 return true;
8336 if (Opc == ISD::BITCAST) // Ignore bitcasts
8337 return isFoldableUseOfShuffle(U);
8338 if (N->hasOneUse()) {
8339 // TODO, there may be some general way to know if a SDNode can
8340 // be folded. We now only know whether an MI is foldable.
8341 if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
8342 return false;
8343 return true;
8344 }
8345 }
8346 return false;
8347}
8348
8350 while (V.getOpcode() == ISD::BITCAST ||
8351 V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8352 V = V.getOperand(0);
8353 return isTargetShuffle(V.getOpcode());
8354}
8355
8356// If the node has a single use by a VSELECT then AVX512 targets may be able to
8357// fold as a predicated instruction.
8358static bool isMaskableNode(SDValue V, const X86Subtarget &Subtarget) {
8359 unsigned SizeInBits = V.getValueSizeInBits();
8360 if ((SizeInBits == 512 && Subtarget.hasAVX512()) ||
8361 (SizeInBits >= 128 && Subtarget.hasVLX())) {
8362 if (V.hasOneUse() && V->user_begin()->getOpcode() == ISD::VSELECT &&
8363 V->user_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
8364 return true;
8365 }
8366 }
8367 return false;
8368}
8369
8370/// Attempt to use the vbroadcast instruction to generate a splat value
8371/// from a splat BUILD_VECTOR which uses:
8372/// a. A single scalar load, or a constant.
8373/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8374///
8375/// The VBROADCAST node is returned when a pattern is found,
8376/// or SDValue() otherwise.
8378 const SDLoc &dl,
8379 const X86Subtarget &Subtarget,
8380 SelectionDAG &DAG) {
8381 // VBROADCAST requires AVX.
8382 // TODO: Splats could be generated for non-AVX CPUs using SSE
8383 // instructions, but there's less potential gain for only 128-bit vectors.
8384 if (!Subtarget.hasAVX())
8385 return SDValue();
8386
8387 MVT VT = BVOp->getSimpleValueType(0);
8388 unsigned NumElts = VT.getVectorNumElements();
8389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8390 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8391 "Unsupported vector type for broadcast.");
8392
8393 // See if the build vector is a repeating sequence of scalars (inc. splat).
8394 SDValue Ld;
8395 BitVector UndefElements;
8396 SmallVector<SDValue, 16> Sequence;
8397 if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
8398 assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
8399 if (Sequence.size() == 1)
8400 Ld = Sequence[0];
8401 }
8402
8403 // Attempt to use VBROADCASTM
8404 // From this pattern:
8405 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8406 // b. t1 = (build_vector t0 t0)
8407 //
8408 // Create (VBROADCASTM v2i1 X)
8409 if (!Sequence.empty() && Subtarget.hasCDI()) {
8410 // If not a splat, are the upper sequence values zeroable?
8411 unsigned SeqLen = Sequence.size();
8412 bool UpperZeroOrUndef =
8413 SeqLen == 1 ||
8414 llvm::all_of(ArrayRef(Sequence).drop_front(),
8415 [](SDValue V) { return !V || isNullConstantOrUndef(V); });
8416 SDValue Op0 = Sequence[0];
8417 if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
8418 (Op0.getOpcode() == ISD::ZERO_EXTEND &&
8419 Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
8420 SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
8421 ? Op0.getOperand(0)
8422 : Op0.getOperand(0).getOperand(0);
8423 MVT MaskVT = BOperand.getSimpleValueType();
8424 MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
8425 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8426 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8427 MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
8428 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
8429 unsigned Scale = 512 / VT.getSizeInBits();
8430 BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
8431 }
8432 SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
8433 if (BcstVT.getSizeInBits() != VT.getSizeInBits())
8434 Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
8435 return DAG.getBitcast(VT, Bcst);
8436 }
8437 }
8438 }
8439
8440 unsigned NumUndefElts = UndefElements.count();
8441 if (!Ld || (NumElts - NumUndefElts) <= 1) {
8442 APInt SplatValue, Undef;
8443 unsigned SplatBitSize;
8444 bool HasUndef;
8445 // Check if this is a repeated constant pattern suitable for broadcasting.
8446 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8447 SplatBitSize > VT.getScalarSizeInBits() &&
8448 SplatBitSize < VT.getSizeInBits()) {
8449 // Avoid replacing with broadcast when it's a use of a shuffle
8450 // instruction to preserve the present custom lowering of shuffles.
8451 if (isFoldableUseOfShuffle(BVOp))
8452 return SDValue();
8453 // replace BUILD_VECTOR with broadcast of the repeated constants.
8454 LLVMContext *Ctx = DAG.getContext();
8455 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8456 if (SplatBitSize == 32 || SplatBitSize == 64 ||
8457 (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8458 // Load the constant scalar/subvector and broadcast it.
8459 MVT CVT = MVT::getIntegerVT(SplatBitSize);
8460 Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8461 SDValue CP = DAG.getConstantPool(C, PVT);
8462 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8463
8464 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8465 SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8466 SDValue Ops[] = {DAG.getEntryNode(), CP};
8467 MachinePointerInfo MPI =
8469 SDValue Brdcst =
8470 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8471 MPI, Alignment, MachineMemOperand::MOLoad);
8472 return DAG.getBitcast(VT, Brdcst);
8473 }
8474 if (SplatBitSize > 64) {
8475 // Load the vector of constants and broadcast it.
8476 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8477 SDValue VCP = DAG.getConstantPool(VecC, PVT);
8478 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8479 MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
8480 Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8481 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8482 SDValue Ops[] = {DAG.getEntryNode(), VCP};
8483 MachinePointerInfo MPI =
8485 return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
8486 Ops, VVT, MPI, Alignment,
8488 }
8489 }
8490
8491 // If we are moving a scalar into a vector (Ld must be set and all elements
8492 // but 1 are undef) and that operation is not obviously supported by
8493 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8494 // That's better than general shuffling and may eliminate a load to GPR and
8495 // move from scalar to vector register.
8496 if (!Ld || NumElts - NumUndefElts != 1)
8497 return SDValue();
8498 unsigned ScalarSize = Ld.getValueSizeInBits();
8499 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8500 return SDValue();
8501 }
8502
8503 bool ConstSplatVal =
8504 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8505 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8506
8507 // TODO: Handle broadcasts of non-constant sequences.
8508
8509 // Make sure that all of the users of a non-constant load are from the
8510 // BUILD_VECTOR node.
8511 // FIXME: Is the use count needed for non-constant, non-load case?
8512 if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8513 return SDValue();
8514
8515 unsigned ScalarSize = Ld.getValueSizeInBits();
8516 bool IsGE256 = (VT.getSizeInBits() >= 256);
8517
8518 // When optimizing for size, generate up to 5 extra bytes for a broadcast
8519 // instruction to save 8 or more bytes of constant pool data.
8520 // TODO: If multiple splats are generated to load the same constant,
8521 // it may be detrimental to overall size. There needs to be a way to detect
8522 // that condition to know if this is truly a size win.
8523 bool OptForSize = DAG.shouldOptForSize();
8524
8525 // Handle broadcasting a single constant scalar from the constant pool
8526 // into a vector.
8527 // On Sandybridge (no AVX2), it is still better to load a constant vector
8528 // from the constant pool and not to broadcast it from a scalar.
8529 // But override that restriction when optimizing for size.
8530 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8531 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8532 EVT CVT = Ld.getValueType();
8533 assert(!CVT.isVector() && "Must not broadcast a vector type");
8534
8535 // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
8536 // For size optimization, also splat v2f64 and v2i64, and for size opt
8537 // with AVX2, also splat i8 and i16.
8538 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8539 if (ScalarSize == 32 ||
8540 (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
8541 (CVT == MVT::f16 && Subtarget.hasAVX2()) ||
8542 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8543 const Constant *C = nullptr;
8545 C = CI->getConstantIntValue();
8547 C = CF->getConstantFPValue();
8548
8549 assert(C && "Invalid constant type");
8550
8551 SDValue CP =
8553 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8554
8555 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8556 SDValue Ops[] = {DAG.getEntryNode(), CP};
8557 MachinePointerInfo MPI =
8559 return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8560 MPI, Alignment, MachineMemOperand::MOLoad);
8561 }
8562 }
8563
8564 // Handle AVX2 in-register broadcasts.
8565 if (!IsLoad && Subtarget.hasInt256() &&
8566 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8567 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8568
8569 // The scalar source must be a normal load.
8570 if (!IsLoad)
8571 return SDValue();
8572
8573 // Make sure the non-chain result is only used by this build vector.
8574 if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
8575 return SDValue();
8576
8577 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8578 (Subtarget.hasVLX() && ScalarSize == 64)) {
8579 auto *LN = cast<LoadSDNode>(Ld);
8580 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8581 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8582 SDValue BCast =
8583 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8584 LN->getMemoryVT(), LN->getMemOperand());
8585 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8586 return BCast;
8587 }
8588
8589 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8590 // double since there is no vbroadcastsd xmm
8591 if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
8592 (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
8593 auto *LN = cast<LoadSDNode>(Ld);
8594 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8595 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8596 SDValue BCast =
8597 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8598 LN->getMemoryVT(), LN->getMemOperand());
8599 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8600 return BCast;
8601 }
8602
8603 if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
8604 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8605
8606 // Unsupported broadcast.
8607 return SDValue();
8608}
8609
8610/// For an EXTRACT_VECTOR_ELT with a constant index return the real
8611/// underlying vector and index.
8612///
8613/// Modifies \p ExtractedFromVec to the real vector and returns the real
8614/// index.
8615static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
8616 SDValue ExtIdx) {
8617 int Idx = ExtIdx->getAsZExtVal();
8618 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
8619 return Idx;
8620
8621 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
8622 // lowered this:
8623 // (extract_vector_elt (v8f32 %1), Constant<6>)
8624 // to:
8625 // (extract_vector_elt (vector_shuffle<2,u,u,u>
8626 // (extract_subvector (v8f32 %0), Constant<4>),
8627 // undef)
8628 // Constant<0>)
8629 // In this case the vector is the extract_subvector expression and the index
8630 // is 2, as specified by the shuffle.
8631 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
8632 SDValue ShuffleVec = SVOp->getOperand(0);
8633 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
8634 assert(ShuffleVecVT.getVectorElementType() ==
8635 ExtractedFromVec.getSimpleValueType().getVectorElementType());
8636
8637 int ShuffleIdx = SVOp->getMaskElt(Idx);
8638 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
8639 ExtractedFromVec = ShuffleVec;
8640 return ShuffleIdx;
8641 }
8642 return Idx;
8643}
8644
8646 SelectionDAG &DAG) {
8647 MVT VT = Op.getSimpleValueType();
8648
8649 // Skip if insert_vec_elt is not supported.
8650 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8652 return SDValue();
8653
8654 unsigned NumElems = Op.getNumOperands();
8655 SDValue VecIn1;
8656 SDValue VecIn2;
8657 SmallVector<unsigned, 4> InsertIndices;
8658 SmallVector<int, 8> Mask(NumElems, -1);
8659
8660 for (unsigned i = 0; i != NumElems; ++i) {
8661 unsigned Opc = Op.getOperand(i).getOpcode();
8662
8663 if (Opc == ISD::POISON || Opc == ISD::UNDEF)
8664 continue;
8665
8667 // Quit if more than 1 elements need inserting.
8668 if (InsertIndices.size() > 1)
8669 return SDValue();
8670
8671 InsertIndices.push_back(i);
8672 continue;
8673 }
8674
8675 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
8676 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
8677
8678 // Quit if non-constant index.
8679 if (!isa<ConstantSDNode>(ExtIdx))
8680 return SDValue();
8681 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
8682
8683 // Quit if extracted from vector of different type.
8684 if (ExtractedFromVec.getValueType() != VT)
8685 return SDValue();
8686
8687 if (!VecIn1.getNode())
8688 VecIn1 = ExtractedFromVec;
8689 else if (VecIn1 != ExtractedFromVec) {
8690 if (!VecIn2.getNode())
8691 VecIn2 = ExtractedFromVec;
8692 else if (VecIn2 != ExtractedFromVec)
8693 // Quit if more than 2 vectors to shuffle
8694 return SDValue();
8695 }
8696
8697 if (ExtractedFromVec == VecIn1)
8698 Mask[i] = Idx;
8699 else if (ExtractedFromVec == VecIn2)
8700 Mask[i] = Idx + NumElems;
8701 }
8702
8703 if (!VecIn1.getNode())
8704 return SDValue();
8705
8706 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getPOISON(VT);
8707 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
8708
8709 for (unsigned Idx : InsertIndices)
8710 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8711 DAG.getVectorIdxConstant(Idx, DL));
8712
8713 return NV;
8714}
8715
8716// Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
8718 const X86Subtarget &Subtarget) {
8719 MVT VT = Op.getSimpleValueType();
8720 MVT SVT = Subtarget.hasFP16() ? MVT::f16 : MVT::i16;
8721 MVT IVT = VT.changeVectorElementType(SVT);
8723 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
8724 NewOps.push_back(DAG.getBitcast(SVT, Op.getOperand(I)));
8725 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
8726 return DAG.getBitcast(VT, Res);
8727}
8728
8729// Lower BUILD_VECTOR operation for vXi1 types.
8731 SelectionDAG &DAG,
8732 const X86Subtarget &Subtarget) {
8733
8734 MVT VT = Op.getSimpleValueType();
8735 assert((VT.getVectorElementType() == MVT::i1) &&
8736 "Unexpected type in LowerBUILD_VECTORvXi1!");
8737 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
8738 ISD::isBuildVectorAllOnes(Op.getNode()))
8739 return Op;
8740
8741 uint64_t Undefs = 0;
8742 uint64_t Immediate = 0;
8743 uint64_t NonConstMask = 0;
8744 SmallSet<SDValue, 16> NonConstElts;
8745 bool HasConstElts = false;
8746 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8747 SDValue In = Op.getOperand(idx);
8748 if (In.isUndef()) {
8749 Undefs |= 1ULL << idx;
8750 continue;
8751 }
8752 if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
8753 Immediate |= (InC->getZExtValue() & 0x1) << idx;
8754 HasConstElts = true;
8755 } else {
8756 NonConstMask |= 1ULL << idx;
8757 NonConstElts.insert(In);
8758 }
8759 }
8760
8761 // for single non-const use " (select i1 elt, imm | elt_mask, imm)"
8762 if (NonConstElts.size() == 1) {
8763 // The build_vector allows the scalar element to be larger than the vector
8764 // element type. We need to mask it to use as a condition unless we know
8765 // the upper bits are zero.
8766 // FIXME: Use computeKnownBits instead of checking specific opcode?
8767 SDValue Cond = *NonConstElts.begin();
8768 assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
8769 if (Cond.getOpcode() != ISD::SETCC)
8770 Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
8771 DAG.getConstant(1, dl, MVT::i8));
8772
8773 uint64_t TrueImm = NonConstMask | Immediate;
8774 uint64_t FalseImm = Immediate;
8775
8776 // Perform the select in the scalar domain so we can use cmov.
8777 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8778 uint64_t TrueLo = (unsigned)TrueImm;
8779 uint64_t TrueHi = TrueImm >> 32;
8780 uint64_t FalseLo = (unsigned)FalseImm;
8781 uint64_t FalseHi = FalseImm >> 32;
8782 SDValue Lo = DAG.getSelect(dl, MVT::i32, Cond,
8783 DAG.getConstant(TrueLo, dl, MVT::i32),
8784 DAG.getConstant(FalseLo, dl, MVT::i32));
8785 SDValue Hi = DAG.getSelect(dl, MVT::i32, Cond,
8786 DAG.getConstant(TrueHi, dl, MVT::i32),
8787 DAG.getConstant(FalseHi, dl, MVT::i32));
8788 Lo = DAG.getBitcast(MVT::v32i1, Lo);
8789 Hi = DAG.getBitcast(MVT::v32i1, Hi);
8790 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
8791 } else {
8792 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8793 // Adjust extended value to -1 as it will improve folding.
8794 if ((TrueImm | Undefs) == (~0ULL >> (64 - VT.getSizeInBits())))
8795 TrueImm = ~0ULL >> (64 - ImmVT.getSizeInBits());
8796 SDValue Select =
8797 DAG.getSelect(dl, ImmVT, Cond, DAG.getConstant(TrueImm, dl, ImmVT),
8798 DAG.getConstant(FalseImm, dl, ImmVT));
8799 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8800 Select = DAG.getBitcast(VecVT, Select);
8801 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
8802 DAG.getVectorIdxConstant(0, dl));
8803 }
8804 }
8805
8806 // See if we can cheaply generate a vXi8 vector and convert to vXi1.
8807 MVT OpVT = Op.getOperand(0).getSimpleValueType();
8808 if (OpVT == MVT::i8 && NonConstMask != 0) {
8809 // On pre-BWI targets, we must extend to vXi32 instead.
8810 MVT ByteVT = VT.changeVectorElementType(MVT::i8);
8811 MVT WideSVT = Subtarget.hasBWI() ? MVT::i8 : MVT::i32;
8812 if (ByteVT.getSizeInBits() < 128) {
8813 WideSVT = ByteVT == MVT::v4i8 ? MVT::i32 : MVT::i64;
8814 ByteVT = MVT::v16i8;
8815 }
8816 MVT WideVT = VT.changeVectorElementType(WideSVT);
8817 if (DAG.getTargetLoweringInfo().isTypeLegal(ByteVT) &&
8818 DAG.getTargetLoweringInfo().isTypeLegal(WideVT)) {
8819 SmallVector<SDValue, 16> Elts(Op->op_values());
8820 Elts.append(ByteVT.getVectorNumElements() - Elts.size(),
8821 DAG.getPOISON(OpVT));
8822 SDValue ByteBV = DAG.getBuildVector(ByteVT, dl, Elts);
8823 SDValue WideBV =
8824 getEXTEND_VECTOR_INREG(ISD::ANY_EXTEND, dl, WideVT, ByteBV, DAG);
8825 WideBV = DAG.getNode(ISD::AND, dl, WideVT, WideBV,
8826 DAG.getConstant(1, dl, WideVT));
8827 return DAG.getSetCC(dl, VT, WideBV, DAG.getConstant(0, dl, WideVT),
8828 ISD::SETNE);
8829 }
8830 }
8831
8832 // insert elements one by one
8833 SDValue DstVec;
8834 if (HasConstElts) {
8835 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8836 SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
8837 SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
8838 ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
8839 ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
8840 DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
8841 } else {
8842 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8843 SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
8844 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8845 DstVec = DAG.getBitcast(VecVT, Imm);
8846 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
8847 DAG.getVectorIdxConstant(0, dl));
8848 }
8849 } else
8850 DstVec = DAG.getUNDEF(VT);
8851
8852 for (unsigned Idx = 0, E = Op.getNumOperands(); Idx != E; ++Idx)
8853 if (NonConstMask & (1ULL << Idx))
8854 DstVec = DAG.getInsertVectorElt(dl, DstVec, Op.getOperand(Idx), Idx);
8855
8856 return DstVec;
8857}
8858
8859[[maybe_unused]] static bool isHorizOp(unsigned Opcode) {
8860 switch (Opcode) {
8861 case X86ISD::PACKSS:
8862 case X86ISD::PACKUS:
8863 case X86ISD::FHADD:
8864 case X86ISD::FHSUB:
8865 case X86ISD::HADD:
8866 case X86ISD::HSUB:
8867 case X86ISD::HADDS:
8868 case X86ISD::HSUBS:
8869 return true;
8870 }
8871 return false;
8872}
8873
8874/// Returns true if is possible to fold MUL and an idiom that has already been
8875/// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8876/// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8877/// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8878///
8879/// Prior to calling this function it should be known that there is some
8880/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8881/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8882/// before replacement of such SDNode with ADDSUB operation. Thus the number
8883/// of \p Opnd0 uses is expected to be equal to 2.
8884/// For example, this function may be called for the following IR:
8885/// %AB = fmul fast <2 x double> %A, %B
8886/// %Sub = fsub fast <2 x double> %AB, %C
8887/// %Add = fadd fast <2 x double> %AB, %C
8888/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8889/// <2 x i32> <i32 0, i32 3>
8890/// There is a def for %Addsub here, which potentially can be replaced by
8891/// X86ISD::ADDSUB operation:
8892/// %Addsub = X86ISD::ADDSUB %AB, %C
8893/// and such ADDSUB can further be replaced with FMADDSUB:
8894/// %Addsub = FMADDSUB %A, %B, %C.
8895///
8896/// The main reason why this method is called before the replacement of the
8897/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8898/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8899/// FMADDSUB is.
8900static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget, SDValue &Opnd0,
8901 SDValue &Opnd1, SDValue &Opnd2,
8902 unsigned ExpectedUses,
8903 bool AllowSubAddOrAddSubContract) {
8904 if (Opnd0.getOpcode() != ISD::FMUL ||
8905 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8906 return false;
8907
8908 // FIXME: These checks must match the similar ones in
8909 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8910 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8911 // or MUL + ADDSUB to FMADDSUB.
8912 bool AllowFusion =
8913 (AllowSubAddOrAddSubContract && Opnd0->getFlags().hasAllowContract());
8914 if (!AllowFusion)
8915 return false;
8916
8917 Opnd2 = Opnd1;
8918 Opnd1 = Opnd0.getOperand(1);
8919 Opnd0 = Opnd0.getOperand(0);
8920
8921 return true;
8922}
8923
8924static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
8925 SelectionDAG &DAG);
8926
8927/// If a BUILD_VECTOR's source elements all apply the same bit operation and
8928/// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8929/// just apply the bit to the vectors.
8930/// NOTE: Its not in our interest to start make a general purpose vectorizer
8931/// from this, but enough scalar bit operations are created from the later
8932/// legalization + scalarization stages to need basic support.
8934 const X86Subtarget &Subtarget,
8935 SelectionDAG &DAG) {
8936 MVT VT = Op->getSimpleValueType(0);
8937 unsigned NumElems = VT.getVectorNumElements();
8938 unsigned ElemSize = VT.getScalarSizeInBits();
8939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8940
8941 // Check that all elements have the same opcode.
8942 // TODO: Should we allow UNDEFS and if so how many?
8943 unsigned Opcode = Op->getOperand(0).getOpcode();
8944 for (unsigned i = 1; i < NumElems; ++i)
8945 if (Opcode != Op->getOperand(i).getOpcode())
8946 return SDValue();
8947
8948 // TODO: We may be able to add support for other Ops (e.g. ADD/SUB).
8949 bool IsShift = false;
8950 switch (Opcode) {
8951 default:
8952 return SDValue();
8953 case ISD::SHL:
8954 case ISD::SRL:
8955 case ISD::SRA:
8956 IsShift = true;
8957 break;
8958 case ISD::AND:
8959 case ISD::XOR:
8960 case ISD::OR:
8961 // Don't do this if the buildvector is a splat - we'd replace one
8962 // constant with an entire vector.
8963 if (Op->getSplatValue())
8964 return SDValue();
8965 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8966 return SDValue();
8967 break;
8968 }
8969
8970 // Collect elements.
8971 bool RHSAllConst = true;
8972 SmallVector<SDValue, 4> LHSElts, RHSElts;
8973 for (SDValue Elt : Op->ops()) {
8974 SDValue LHS = Elt.getOperand(0);
8975 SDValue RHS = Elt.getOperand(1);
8976 RHSAllConst &= isa<ConstantSDNode>(RHS);
8977 LHSElts.push_back(LHS);
8978 RHSElts.push_back(RHS);
8979 }
8980
8981 // Canonicalize shift amounts.
8982 if (IsShift) {
8983 // We expect the canonicalized RHS operand to be the constant.
8984 // TODO: Permit non-constant XOP/AVX2 cases?
8985 if (!RHSAllConst)
8986 return SDValue();
8987
8988 // Extend shift amounts.
8989 for (SDValue &Op1 : RHSElts)
8990 if (Op1.getValueSizeInBits() != ElemSize)
8991 Op1 = DAG.getZExtOrTrunc(Op1, DL, VT.getScalarType());
8992
8993 // Limit to shifts by uniform immediates.
8994 // TODO: Only accept vXi8/vXi64 special cases?
8995 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
8996 if (any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
8997 return SDValue();
8998 }
8999 assert(all_of(llvm::concat<SDValue>(LHSElts, RHSElts),
9000 [ElemSize](SDValue V) {
9001 return V.getValueSizeInBits() == ElemSize;
9002 }) &&
9003 "Element size mismatch");
9004
9005 // To avoid an increase in GPR->FPU instructions, LHS/RHS must be foldable as
9006 // a load or RHS must be constant.
9007 SDValue LHS = EltsFromConsecutiveLoads(VT, LHSElts, DL, DAG, Subtarget,
9008 /*IsAfterLegalize=*/true);
9009 SDValue RHS = EltsFromConsecutiveLoads(VT, RHSElts, DL, DAG, Subtarget,
9010 /*IsAfterLegalize=*/true);
9011 if (!LHS && !RHS && !RHSAllConst)
9012 return SDValue();
9013
9014 if (!LHS)
9015 LHS = DAG.getBuildVector(VT, DL, LHSElts);
9016 if (!RHS)
9017 RHS = DAG.getBuildVector(VT, DL, RHSElts);
9018 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9019
9020 if (!IsShift)
9021 return Res;
9022
9023 // Immediately lower the shift to ensure the constant build vector doesn't
9024 // get converted to a constant pool before the shift is lowered.
9025 return LowerShift(Res, Subtarget, DAG);
9026}
9027
9028static bool isShuffleFoldableLoad(SDValue);
9029
9030/// Attempt to lower a BUILD_VECTOR of scalar values to a shuffle of splats
9031/// representing a blend.
9033 X86Subtarget const &Subtarget,
9034 SelectionDAG &DAG) {
9035 MVT VT = BVOp->getSimpleValueType(0u);
9036
9037 if (VT != MVT::v4f64)
9038 return SDValue();
9039
9040 // Collect unique operands.
9041 auto UniqueOps = SmallSet<SDValue, 16u>();
9042 for (SDValue Op : BVOp->ops()) {
9043 if (isIntOrFPConstant(Op) || Op.isUndef())
9044 return SDValue();
9045 UniqueOps.insert(Op);
9046 }
9047
9048 // Candidate BUILD_VECTOR must have 2 unique operands.
9049 if (UniqueOps.size() != 2u)
9050 return SDValue();
9051
9052 SDValue Op0 = BVOp->getOperand(0u);
9053 UniqueOps.erase(Op0);
9054 SDValue Op1 = *UniqueOps.begin();
9055
9056 if (Subtarget.hasAVX2() || isShuffleFoldableLoad(Op0) ||
9057 isShuffleFoldableLoad(Op1)) {
9058 // Create shuffle mask.
9059 auto const NumElems = VT.getVectorNumElements();
9060 SmallVector<int, 16u> Mask(NumElems);
9061 for (auto I = 0u; I < NumElems; ++I) {
9062 SDValue Op = BVOp->getOperand(I);
9063 Mask[I] = Op == Op0 ? I : I + NumElems;
9064 }
9065 // Create shuffle of splats.
9066 SDValue NewOp0 = DAG.getSplatBuildVector(VT, DL, Op0);
9067 SDValue NewOp1 = DAG.getSplatBuildVector(VT, DL, Op1);
9068 return DAG.getVectorShuffle(VT, DL, NewOp0, NewOp1, Mask);
9069 }
9070
9071 return SDValue();
9072}
9073
9074/// Widen a BUILD_VECTOR if the scalar operands are freely mergeable.
9076 X86Subtarget const &Subtarget,
9077 SelectionDAG &DAG) {
9078 using namespace SDPatternMatch;
9079 MVT VT = BVOp->getSimpleValueType(0);
9080 MVT SVT = VT.getScalarType();
9081 unsigned NumElts = VT.getVectorNumElements();
9082 unsigned EltBits = SVT.getSizeInBits();
9083
9084 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
9085 return SDValue();
9086
9087 unsigned WideBits = 2 * EltBits;
9088 MVT WideSVT = MVT::getIntegerVT(WideBits);
9089 MVT WideVT = MVT::getVectorVT(WideSVT, NumElts / 2);
9090 if (!DAG.getTargetLoweringInfo().isTypeLegal(WideSVT))
9091 return SDValue();
9092
9094 for (unsigned I = 0; I != NumElts; I += 2) {
9095 SDValue Op0 = BVOp->getOperand(I + 0);
9096 SDValue Op1 = BVOp->getOperand(I + 1);
9097
9098 if (Op0.isUndef() && Op1.isUndef()) {
9099 WideOps.push_back(DAG.getUNDEF(WideSVT));
9100 continue;
9101 }
9102
9103 // TODO: Constant repacking?
9104
9105 // Merge scalars that have been split from the same source.
9106 SDValue X, Y;
9107 if (sd_match(Op0, m_Trunc(m_Value(X))) &&
9108 sd_match(Op1, m_Trunc(m_Srl(m_Value(Y), m_SpecificInt(EltBits)))) &&
9110 X.getValueType().bitsGE(WideSVT)) {
9111 if (X.getValueType().bitsGT(WideSVT))
9112 X = DAG.getNode(ISD::TRUNCATE, DL, WideSVT, X);
9113 WideOps.push_back(X);
9114 continue;
9115 }
9116
9117 return SDValue();
9118 }
9119
9120 assert(WideOps.size() == (NumElts / 2) && "Failed to widen build vector");
9121 return DAG.getBitcast(VT, DAG.getBuildVector(WideVT, DL, WideOps));
9122}
9123
9124/// Create a vector constant without a load. SSE/AVX provide the bare minimum
9125/// functionality to do this, so it's all zeros, all ones, or some derivation
9126/// that is cheap to calculate.
9128 SelectionDAG &DAG,
9129 const X86Subtarget &Subtarget) {
9130 MVT VT = Op.getSimpleValueType();
9131
9132 // Vectors containing all zeros can be matched by pxor and xorps.
9133 if (ISD::isBuildVectorAllZeros(Op.getNode()))
9134 return Op;
9135
9136 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9137 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9138 // vpcmpeqd on 256-bit vectors.
9139 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9140 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9141 return Op;
9142
9143 return getOnesVector(VT, DAG, DL);
9144 }
9145
9146 return SDValue();
9147}
9148
9149/// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9150/// from a vector of source values and a vector of extraction indices.
9151/// The vectors might be manipulated to match the type of the permute op.
9152static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9153 const SDLoc &DL, SelectionDAG &DAG,
9154 const X86Subtarget &Subtarget) {
9155 MVT ShuffleVT = VT;
9156 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9157 unsigned NumElts = VT.getVectorNumElements();
9158 unsigned SizeInBits = VT.getSizeInBits();
9159
9160 // Adjust IndicesVec to match VT size.
9161 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9162 "Illegal variable permute mask size");
9163 if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
9164 // Narrow/widen the indices vector to the correct size.
9165 if (IndicesVec.getValueSizeInBits() > SizeInBits)
9166 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9167 NumElts * VT.getScalarSizeInBits());
9168 else if (IndicesVec.getValueSizeInBits() < SizeInBits)
9169 IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
9170 SDLoc(IndicesVec), SizeInBits);
9171 // Zero-extend the index elements within the vector.
9172 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9173 IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
9174 IndicesVT, IndicesVec);
9175 }
9176 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9177
9178 // Handle SrcVec that don't match VT type.
9179 if (SrcVec.getValueSizeInBits() != SizeInBits) {
9180 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9181 // Handle larger SrcVec by treating it as a larger permute.
9182 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9183 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9184 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9185 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9186 Subtarget, DAG, SDLoc(IndicesVec));
9187 SDValue NewSrcVec =
9188 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9189 if (NewSrcVec)
9190 return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
9191 return SDValue();
9192 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9193 // Widen smaller SrcVec to match VT.
9194 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9195 } else
9196 return SDValue();
9197 }
9198
9199 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9200 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9201 EVT SrcVT = Idx.getValueType();
9202 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9203 uint64_t IndexScale = 0;
9204 uint64_t IndexOffset = 0;
9205
9206 // If we're scaling a smaller permute op, then we need to repeat the
9207 // indices, scaling and offsetting them as well.
9208 // e.g. v4i32 -> v16i8 (Scale = 4)
9209 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9210 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9211 for (uint64_t i = 0; i != Scale; ++i) {
9212 IndexScale |= Scale << (i * NumDstBits);
9213 IndexOffset |= i << (i * NumDstBits);
9214 }
9215
9216 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9217 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9218 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9219 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9220 return Idx;
9221 };
9222
9223 unsigned Opcode = 0;
9224 switch (VT.SimpleTy) {
9225 default:
9226 break;
9227 case MVT::v16i8:
9228 if (Subtarget.hasSSSE3())
9229 Opcode = X86ISD::PSHUFB;
9230 break;
9231 case MVT::v8i16:
9232 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9233 Opcode = X86ISD::VPERMV;
9234 else if (Subtarget.hasSSSE3()) {
9235 Opcode = X86ISD::PSHUFB;
9236 ShuffleVT = MVT::v16i8;
9237 }
9238 break;
9239 case MVT::v4f32:
9240 case MVT::v4i32:
9241 if (Subtarget.hasAVX()) {
9242 Opcode = X86ISD::VPERMILPV;
9243 ShuffleVT = MVT::v4f32;
9244 } else if (Subtarget.hasSSSE3()) {
9245 Opcode = X86ISD::PSHUFB;
9246 ShuffleVT = MVT::v16i8;
9247 }
9248 break;
9249 case MVT::v2f64:
9250 case MVT::v2i64:
9251 if (Subtarget.hasAVX()) {
9252 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
9253 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9254 Opcode = X86ISD::VPERMILPV;
9255 ShuffleVT = MVT::v2f64;
9256 } else if (Subtarget.hasSSE41()) {
9257 // SSE41 can compare v2i64 - select between indices 0 and 1.
9258 return DAG.getSelectCC(
9259 DL, IndicesVec,
9260 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
9261 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
9262 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
9264 }
9265 break;
9266 case MVT::v32i8:
9267 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
9268 Opcode = X86ISD::VPERMV;
9269 else if (Subtarget.hasXOP()) {
9270 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
9271 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
9272 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
9273 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
9274 return DAG.getNode(
9276 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
9277 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
9278 } else if (Subtarget.hasAVX()) {
9279 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
9280 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
9281 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
9282 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
9283 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
9285 // Permute Lo and Hi and then select based on index range.
9286 // This works as SHUFB uses bits[3:0] to permute elements and we don't
9287 // care about the bit[7] as its just an index vector.
9288 SDValue Idx = Ops[2];
9289 EVT VT = Idx.getValueType();
9290 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
9291 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
9292 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
9294 };
9295 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
9296 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
9297 PSHUFBBuilder);
9298 }
9299 break;
9300 case MVT::v16i16:
9301 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9302 Opcode = X86ISD::VPERMV;
9303 else if (Subtarget.hasAVX()) {
9304 // Scale to v32i8 and perform as v32i8.
9305 IndicesVec = ScaleIndices(IndicesVec, 2);
9306 return DAG.getBitcast(
9308 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
9309 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
9310 }
9311 break;
9312 case MVT::v8f32:
9313 case MVT::v8i32:
9314 if (Subtarget.hasAVX2())
9315 Opcode = X86ISD::VPERMV;
9316 else if (Subtarget.hasAVX()) {
9317 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
9318 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9319 {0, 1, 2, 3, 0, 1, 2, 3});
9320 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9321 {4, 5, 6, 7, 4, 5, 6, 7});
9322 if (Subtarget.hasXOP())
9323 return DAG.getBitcast(
9324 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
9325 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9326 // Permute Lo and Hi and then select based on index range.
9327 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
9328 SDValue Res = DAG.getSelectCC(
9329 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
9330 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
9331 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
9333 return DAG.getBitcast(VT, Res);
9334 }
9335 break;
9336 case MVT::v4i64:
9337 case MVT::v4f64:
9338 if (Subtarget.hasAVX512()) {
9339 if (!Subtarget.hasVLX()) {
9340 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9341 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9342 SDLoc(SrcVec));
9343 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9344 DAG, SDLoc(IndicesVec));
9345 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9346 DAG, Subtarget);
9347 return extract256BitVector(Res, 0, DAG, DL);
9348 }
9349 Opcode = X86ISD::VPERMV;
9350 } else if (Subtarget.hasAVX()) {
9351 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9352 SDValue LoLo =
9353 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9354 SDValue HiHi =
9355 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9356 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
9357 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9358 if (Subtarget.hasXOP())
9359 return DAG.getBitcast(
9360 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
9361 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9362 // Permute Lo and Hi and then select based on index range.
9363 // This works as VPERMILPD only uses index bit[1] to permute elements.
9364 SDValue Res = DAG.getSelectCC(
9365 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
9366 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
9367 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
9369 return DAG.getBitcast(VT, Res);
9370 }
9371 break;
9372 case MVT::v64i8:
9373 if (Subtarget.hasVBMI())
9374 Opcode = X86ISD::VPERMV;
9375 break;
9376 case MVT::v32i16:
9377 if (Subtarget.hasBWI())
9378 Opcode = X86ISD::VPERMV;
9379 break;
9380 case MVT::v16f32:
9381 case MVT::v16i32:
9382 case MVT::v8f64:
9383 case MVT::v8i64:
9384 if (Subtarget.hasAVX512())
9385 Opcode = X86ISD::VPERMV;
9386 break;
9387 }
9388 if (!Opcode)
9389 return SDValue();
9390
9391 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
9392 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
9393 "Illegal variable permute shuffle type");
9394
9395 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
9396 if (Scale > 1)
9397 IndicesVec = ScaleIndices(IndicesVec, Scale);
9398
9399 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
9400 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
9401
9402 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
9403 SDValue Res = Opcode == X86ISD::VPERMV
9404 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
9405 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
9406 return DAG.getBitcast(VT, Res);
9407}
9408
9409// Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
9410// reasoned to be a permutation of a vector by indices in a non-constant vector.
9411// (build_vector (extract_elt V, (extract_elt I, 0)),
9412// (extract_elt V, (extract_elt I, 1)),
9413// ...
9414// ->
9415// (vpermv I, V)
9416//
9417// TODO: Handle undefs
9418// TODO: Utilize pshufb and zero mask blending to support more efficient
9419// construction of vectors with constant-0 elements.
9420static SDValue
9422 SelectionDAG &DAG,
9423 const X86Subtarget &Subtarget) {
9424 SDValue SrcVec, IndicesVec;
9425
9426 // Check for a match of the permute source vector and permute index elements.
9427 // This is done by checking that the i-th build_vector operand is of the form:
9428 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
9429 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
9430 SDValue Op = peekThroughOneUseFreeze(V.getOperand(Idx));
9431 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9432 return SDValue();
9433
9434 // If this is the first extract encountered in V, set the source vector,
9435 // otherwise verify the extract is from the previously defined source
9436 // vector.
9437 if (!SrcVec)
9438 SrcVec = Op.getOperand(0);
9439 else if (SrcVec != Op.getOperand(0))
9440 return SDValue();
9441 SDValue ExtractedIndex = Op->getOperand(1);
9442 // Peek through extends.
9443 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
9444 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
9445 ExtractedIndex = ExtractedIndex.getOperand(0);
9446 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9447 return SDValue();
9448
9449 // If this is the first extract from the index vector candidate, set the
9450 // indices vector, otherwise verify the extract is from the previously
9451 // defined indices vector.
9452 if (!IndicesVec)
9453 IndicesVec = ExtractedIndex.getOperand(0);
9454 else if (IndicesVec != ExtractedIndex.getOperand(0))
9455 return SDValue();
9456
9457 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
9458 if (!PermIdx || PermIdx->getAPIntValue() != Idx)
9459 return SDValue();
9460 }
9461
9462 MVT VT = V.getSimpleValueType();
9463 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9464}
9465
9466SDValue
9467X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
9468 SDLoc dl(Op);
9469
9470 MVT VT = Op.getSimpleValueType();
9471 MVT EltVT = VT.getVectorElementType();
9472 MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
9473 unsigned NumElems = Op.getNumOperands();
9474
9475 // Generate vectors for predicate vectors.
9476 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
9477 return LowerBUILD_VECTORvXi1(Op, dl, DAG, Subtarget);
9478
9479 if (VT.getVectorElementType() == MVT::bf16 &&
9480 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16()))
9481 return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
9482
9483 if (SDValue VectorCst = materializeVectorConstant(Op, dl, DAG, Subtarget))
9484 return VectorCst;
9485
9486 unsigned EVTBits = EltVT.getSizeInBits();
9487 APInt UndefMask = APInt::getZero(NumElems);
9488 APInt FrozenUndefMask = APInt::getZero(NumElems);
9489 APInt ZeroMask = APInt::getZero(NumElems);
9490 APInt NonZeroMask = APInt::getZero(NumElems);
9491 bool IsAllConstants = true;
9492 bool OneUseFrozenUndefs = true;
9493 SmallSet<SDValue, 8> Values;
9494 unsigned NumConstants = NumElems;
9495 for (unsigned i = 0; i < NumElems; ++i) {
9496 SDValue Elt = Op.getOperand(i);
9497 if (Elt.isUndef()) {
9498 UndefMask.setBit(i);
9499 continue;
9500 }
9501 if (ISD::isFreezeUndef(Elt.getNode())) {
9502 OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
9503 FrozenUndefMask.setBit(i);
9504 continue;
9505 }
9506 Values.insert(Elt);
9507 if (!isIntOrFPConstant(Elt)) {
9508 IsAllConstants = false;
9509 NumConstants--;
9510 }
9511 if (X86::isZeroNode(Elt)) {
9512 ZeroMask.setBit(i);
9513 } else {
9514 NonZeroMask.setBit(i);
9515 }
9516 }
9517
9518 // All undef vector. Return an UNDEF.
9519 if (UndefMask.isAllOnes())
9520 return DAG.getUNDEF(VT);
9521
9522 // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
9523 if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
9524 return DAG.getFreeze(DAG.getUNDEF(VT));
9525
9526 // All undef/freeze(undef)/zero vector. Return a zero vector.
9527 if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
9528 return getZeroVector(VT, Subtarget, DAG, dl);
9529
9530 // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
9531 // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
9532 // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
9533 // and blend the FREEZE-UNDEF operands back in.
9534 // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
9535 if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
9536 NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
9537 SmallVector<int, 16> BlendMask(NumElems, -1);
9538 SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
9539 for (unsigned i = 0; i < NumElems; ++i) {
9540 if (UndefMask[i]) {
9541 BlendMask[i] = -1;
9542 continue;
9543 }
9544 BlendMask[i] = i;
9545 if (!FrozenUndefMask[i])
9546 Elts[i] = Op.getOperand(i);
9547 else
9548 BlendMask[i] += NumElems;
9549 }
9550 SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
9551 SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
9552 SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
9553 return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
9554 }
9555
9556 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9557
9558 // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
9559 // be better off lowering to a smaller build vector and padding with
9560 // undef/zero.
9561 if ((VT.is256BitVector() || VT.is512BitVector()) &&
9563 unsigned UpperElems = NumElems / 2;
9564 APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
9565 unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
9566 if (NumUpperUndefsOrZeros >= UpperElems) {
9567 if (VT.is512BitVector() &&
9568 NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
9569 UpperElems = NumElems - (NumElems / 4);
9570 // If freeze(undef) is in any upper elements, force to zero.
9571 bool UndefUpper = UndefMask.countl_one() >= UpperElems;
9572 MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
9573 SDValue NewBV =
9574 DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
9575 return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
9576 }
9577 }
9578
9579 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, dl, Subtarget, DAG))
9580 return Broadcast;
9581 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, dl, Subtarget, DAG))
9582 return BitOp;
9583 if (SDValue Blend = lowerBuildVectorAsBlend(BV, dl, Subtarget, DAG))
9584 return Blend;
9585 if (SDValue WideBV = widenBuildVector(BV, dl, Subtarget, DAG))
9586 return WideBV;
9587
9588 unsigned NumZero = ZeroMask.popcount();
9589 unsigned NumNonZero = NonZeroMask.popcount();
9590
9591 // If we are inserting one variable into a vector of non-zero constants, try
9592 // to avoid loading each constant element as a scalar. Load the constants as a
9593 // vector and then insert the variable scalar element. If insertion is not
9594 // supported, fall back to a shuffle to get the scalar blended with the
9595 // constants. Insertion into a zero vector is handled as a special-case
9596 // somewhere below here.
9597 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9598 FrozenUndefMask.isZero() &&
9601 // Create an all-constant vector. The variable element in the old
9602 // build vector is replaced by undef in the constant vector. Save the
9603 // variable scalar element and its index for use in the insertelement.
9604 LLVMContext &Context = *DAG.getContext();
9605 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9606 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9607 SDValue VarElt;
9608 SDValue InsIndex;
9609 for (unsigned i = 0; i != NumElems; ++i) {
9610 SDValue Elt = Op.getOperand(i);
9611 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9612 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9613 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9614 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9615 else if (!Elt.isUndef()) {
9616 assert(!VarElt.getNode() && !InsIndex.getNode() &&
9617 "Expected one variable element in this vector");
9618 VarElt = Elt;
9619 InsIndex = DAG.getVectorIdxConstant(i, dl);
9620 }
9621 }
9622 Constant *CV = ConstantVector::get(ConstVecOps);
9623 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9624
9625 // The constants we just created may not be legal (eg, floating point). We
9626 // must lower the vector right here because we can not guarantee that we'll
9627 // legalize it before loading it. This is also why we could not just create
9628 // a new build vector here. If the build vector contains illegal constants,
9629 // it could get split back up into a series of insert elements.
9630 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9631 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9633 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9634 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9635 unsigned InsertC = InsIndex->getAsZExtVal();
9636 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9637 if (InsertC < NumEltsInLow128Bits)
9638 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9639
9640 // There's no good way to insert into the high elements of a >128-bit
9641 // vector, so use shuffles to avoid an extract/insert sequence.
9642 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
9643 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
9644 SmallVector<int, 8> ShuffleMask;
9645 unsigned NumElts = VT.getVectorNumElements();
9646 for (unsigned i = 0; i != NumElts; ++i)
9647 ShuffleMask.push_back(i == InsertC ? NumElts : i);
9648 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9649 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9650 }
9651
9652 // Special case for single non-zero, non-undef, element.
9653 if (NumNonZero == 1) {
9654 unsigned Idx = NonZeroMask.countr_zero();
9655 SDValue Item = Op.getOperand(Idx);
9656
9657 // If we have a constant or non-constant insertion into the low element of
9658 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9659 // the rest of the elements. This will be matched as movd/movq/movss/movsd
9660 // depending on what the source datatype is.
9661 if (Idx == 0) {
9662 if (NumZero == 0)
9663 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9664
9665 if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
9666 EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
9667 (EltVT == MVT::i16 && Subtarget.hasFP16())) {
9668 assert((VT.is128BitVector() || VT.is256BitVector() ||
9669 VT.is512BitVector()) &&
9670 "Expected an SSE value type!");
9671 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9672 // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
9673 // zero vector.
9674 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9675 }
9676
9677 // We can't directly insert an i8 or i16 into a vector, so zero extend
9678 // it to i32 first.
9679 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9680 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9681 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
9682 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9683 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9684 return DAG.getBitcast(VT, Item);
9685 }
9686 }
9687
9688 // Is it a vector logical left shift?
9689 if (NumElems == 2 && Idx == 1 &&
9690 X86::isZeroNode(Op.getOperand(0)) &&
9691 !X86::isZeroNode(Op.getOperand(1))) {
9692 unsigned NumBits = VT.getSizeInBits();
9693 return getVShift(true, VT,
9695 VT, Op.getOperand(1)),
9696 NumBits/2, DAG, *this, dl);
9697 }
9698
9699 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9700 return SDValue();
9701
9702 // Otherwise, if this is a vector with i32 or f32 elements, and the element
9703 // is a non-constant being inserted into an element other than the low one,
9704 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
9705 // movd/movss) to move this into the low element, then shuffle it into
9706 // place.
9707 if (EVTBits == 32) {
9708 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9709 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9710 }
9711 }
9712
9713 // Splat is obviously ok. Let legalizer expand it to a shuffle.
9714 if (Values.size() == 1) {
9715 if (EVTBits == 32) {
9716 // Instead of a shuffle like this:
9717 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9718 // Check if it's possible to issue this instead.
9719 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9720 unsigned Idx = NonZeroMask.countr_zero();
9721 SDValue Item = Op.getOperand(Idx);
9722 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9723 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9724 }
9725 return SDValue();
9726 }
9727
9728 // A vector full of immediates; various special cases are already
9729 // handled, so this is best done with a single constant-pool load.
9730 if (IsAllConstants)
9731 return SDValue();
9732
9733 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, dl, DAG, Subtarget))
9734 return V;
9735
9736 // See if we can use a vector load to get all of the elements.
9737 {
9738 SmallVector<SDValue, 64> Ops(Op->ops().take_front(NumElems));
9739 if (SDValue LD =
9740 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9741 return LD;
9742 }
9743
9744 // If this is a splat of pairs of 32-bit elements, we can use a narrower
9745 // build_vector and broadcast it.
9746 // TODO: We could probably generalize this more.
9747 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9748 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9749 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9750 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9751 // Make sure all the even/odd operands match.
9752 for (unsigned i = 2; i != NumElems; ++i)
9753 if (Ops[i % 2] != Op.getOperand(i))
9754 return false;
9755 return true;
9756 };
9757 if (CanSplat(Op, NumElems, Ops)) {
9758 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9759 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9760 // Create a new build vector and cast to v2i64/v2f64.
9761 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9762 DAG.getBuildVector(NarrowVT, dl, Ops));
9763 // Broadcast from v2i64/v2f64 and cast to final VT.
9764 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
9765 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9766 NewBV));
9767 }
9768 }
9769
9770 // For AVX-length vectors, build the individual 128-bit pieces and use
9771 // shuffles to put them in place.
9772 if (VT.getSizeInBits() > 128) {
9773 MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
9774
9775 // Build both the lower and upper subvector.
9776 SDValue Lower =
9777 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9778 SDValue Upper = DAG.getBuildVector(
9779 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9780
9781 // Recreate the wider vector with the lower and upper part.
9782 return concatSubVectors(Lower, Upper, DAG, dl);
9783 }
9784
9785 // Let legalizer expand 2-wide build_vectors.
9786 if (EVTBits == 64) {
9787 if (NumNonZero == 1) {
9788 // One half is zero or undef.
9789 unsigned Idx = NonZeroMask.countr_zero();
9790 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9791 Op.getOperand(Idx));
9792 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9793 }
9794 return SDValue();
9795 }
9796
9797 // If element VT is < 32 bits, convert it to inserts into a zero vector.
9798 if (EVTBits == 8 && NumElems == 16)
9799 if (SDValue V = LowerBuildVectorv16i8(Op, dl, NonZeroMask, NumNonZero,
9800 NumZero, DAG, Subtarget))
9801 return V;
9802
9803 if (EltVT == MVT::i16 && NumElems == 8)
9804 if (SDValue V = LowerBuildVectorv8i16(Op, dl, NonZeroMask, NumNonZero,
9805 NumZero, DAG, Subtarget))
9806 return V;
9807
9808 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9809 if (EVTBits == 32 && NumElems == 4)
9810 if (SDValue V = LowerBuildVectorv4x32(Op, dl, DAG, Subtarget))
9811 return V;
9812
9813 // If element VT is == 32 bits, turn it into a number of shuffles.
9814 if (NumElems == 4 && NumZero > 0) {
9815 SmallVector<SDValue, 8> Ops(NumElems);
9816 for (unsigned i = 0; i < 4; ++i) {
9817 bool isZero = !NonZeroMask[i];
9818 if (isZero)
9819 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9820 else
9821 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9822 }
9823
9824 for (unsigned i = 0; i < 2; ++i) {
9825 switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
9826 default: llvm_unreachable("Unexpected NonZero count");
9827 case 0:
9828 Ops[i] = Ops[i*2]; // Must be a zero vector.
9829 break;
9830 case 1:
9831 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9832 break;
9833 case 2:
9834 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9835 break;
9836 case 3:
9837 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9838 break;
9839 }
9840 }
9841
9842 bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
9843 bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
9844 int MaskVec[] = {
9845 Reverse1 ? 1 : 0,
9846 Reverse1 ? 0 : 1,
9847 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9848 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
9849 };
9850 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9851 }
9852
9853 assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9854
9855 // Check for a build vector from mostly shuffle plus few inserting.
9856 if (SDValue Sh = buildFromShuffleMostly(Op, dl, DAG))
9857 return Sh;
9858
9859 // For SSE 4.1, use insertps to put the high elements into the low element.
9860 if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
9861 SDValue Result;
9862 if (!Op.getOperand(0).isUndef())
9863 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9864 else
9865 Result = DAG.getUNDEF(VT);
9866
9867 for (unsigned i = 1; i < NumElems; ++i) {
9868 if (Op.getOperand(i).isUndef()) continue;
9869 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9870 Op.getOperand(i), DAG.getVectorIdxConstant(i, dl));
9871 }
9872 return Result;
9873 }
9874
9875 // Otherwise, expand into a number of unpckl*, start by extending each of
9876 // our (non-undef) elements to the full vector width with the element in the
9877 // bottom slot of the vector (which generates no code for SSE).
9878 SmallVector<SDValue, 8> Ops(NumElems);
9879 for (unsigned i = 0; i < NumElems; ++i) {
9880 if (!Op.getOperand(i).isUndef())
9881 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9882 else
9883 Ops[i] = DAG.getUNDEF(VT);
9884 }
9885
9886 // Next, we iteratively mix elements, e.g. for v4f32:
9887 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9888 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9889 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
9890 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9891 // Generate scaled UNPCKL shuffle mask.
9892 SmallVector<int, 16> Mask;
9893 for(unsigned i = 0; i != Scale; ++i)
9894 Mask.push_back(i);
9895 for (unsigned i = 0; i != Scale; ++i)
9896 Mask.push_back(NumElems+i);
9897 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9898
9899 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9900 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9901 }
9902 return Ops[0];
9903}
9904
9905// 256-bit AVX can use the vinsertf128 instruction
9906// to create 256-bit vectors from two other 128-bit ones.
9907// TODO: Detect subvector broadcast here instead of DAG combine?
9909 SelectionDAG &DAG,
9910 const X86Subtarget &Subtarget) {
9911 MVT ResVT = Op.getSimpleValueType();
9912 assert((ResVT.is256BitVector() || ResVT.is512BitVector()) &&
9913 "Value type must be 256-/512-bit wide");
9914
9916 unsigned NumSubElems = Ops[0].getSimpleValueType().getVectorNumElements();
9917 unsigned NumOperands = Op.getNumOperands();
9918
9919 unsigned NumFreezeUndef = 0;
9920 unsigned NumZero = 0;
9921 unsigned NumNonZero = 0;
9922 unsigned NonZeros = 0;
9923 SmallSet<SDValue, 4> Undefs;
9924 for (auto [I, SubVec] : enumerate(Ops)) {
9925 if (SubVec.isUndef())
9926 continue;
9927 if (ISD::isFreezeUndef(SubVec.getNode())) {
9928 // If the freeze(undef) has multiple uses then we must fold to zero.
9929 if (SubVec.hasOneUse()) {
9930 ++NumFreezeUndef;
9931 } else {
9932 ++NumZero;
9933 Undefs.insert(SubVec);
9934 }
9935 } else if (ISD::isBuildVectorAllZeros(SubVec.getNode())) {
9936 ++NumZero;
9937 } else {
9938 assert(I < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9939 NonZeros |= 1 << I;
9940 ++NumNonZero;
9941 }
9942 }
9943
9944 // If we have more than 2 non-zeros, build each half separately.
9945 if (NumNonZero > 2) {
9946 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9947 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9948 ArrayRef<SDValue>(Ops).slice(0, NumOperands / 2));
9949 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9950 ArrayRef<SDValue>(Ops).slice(NumOperands / 2));
9951 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9952 }
9953
9954 // Otherwise, build it up through insert_subvectors.
9955 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9956 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
9957 : DAG.getUNDEF(ResVT));
9958
9959 // Replace Undef operands with ZeroVector.
9960 for (SDValue U : Undefs)
9962 U, getZeroVector(U.getSimpleValueType(), Subtarget, DAG, dl));
9963
9964 for (auto [I, SubVec] : enumerate(Ops)) {
9965 if ((NonZeros & (1 << I)) == 0)
9966 continue;
9967
9968 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9969 DAG.getVectorIdxConstant(I * NumSubElems, dl));
9970 }
9971
9972 return Vec;
9973}
9974
9975// Returns true if the given node is a type promotion (by concatenating i1
9976// zeros) of the result of a node that already zeros all upper bits of
9977// k-register.
9978// TODO: Merge this with LowerAVXCONCAT_VECTORS?
9980 const X86Subtarget &Subtarget,
9981 SelectionDAG & DAG) {
9982 MVT ResVT = Op.getSimpleValueType();
9983 unsigned NumOperands = Op.getNumOperands();
9984 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9985 "Unexpected number of operands in CONCAT_VECTORS");
9986
9987 uint64_t Zeros = 0;
9988 uint64_t NonZeros = 0;
9989 for (unsigned i = 0; i != NumOperands; ++i) {
9990 SDValue SubVec = Op.getOperand(i);
9991 if (SubVec.isUndef())
9992 continue;
9993 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9994 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9995 Zeros |= (uint64_t)1 << i;
9996 else
9997 NonZeros |= (uint64_t)1 << i;
9998 }
9999
10000 unsigned NumElems = ResVT.getVectorNumElements();
10001
10002 // If we are inserting non-zero vector and there are zeros in LSBs and undef
10003 // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10004 // insert_subvector will give us two kshifts.
10005 if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10006 Log2_64(NonZeros) != NumOperands - 1) {
10007 unsigned Idx = Log2_64(NonZeros);
10008 SDValue SubVec = Op.getOperand(Idx);
10009 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10010 MVT ShiftVT = widenMaskVectorType(ResVT, Subtarget);
10011 Op = widenSubVector(ShiftVT, SubVec, false, Subtarget, DAG, dl);
10012 Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, Op,
10013 DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10014 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10015 DAG.getVectorIdxConstant(0, dl));
10016 }
10017
10018 // If there are zero or one non-zeros we can handle this very simply.
10019 if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10020 SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10021 if (!NonZeros)
10022 return Vec;
10023 unsigned Idx = Log2_64(NonZeros);
10024 SDValue SubVec = Op.getOperand(Idx);
10025 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10026 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10027 DAG.getVectorIdxConstant(Idx * SubVecNumElts, dl));
10028 }
10029
10030 if (NumOperands > 2) {
10031 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10032 ArrayRef<SDUse> Ops = Op->ops();
10033 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10034 Ops.slice(0, NumOperands / 2));
10035 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10036 Ops.slice(NumOperands / 2));
10037 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10038 }
10039
10040 assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
10041
10042 if (ResVT.getVectorNumElements() >= 16)
10043 return Op; // The operation is legal with KUNPCK
10044
10045 SDValue Vec =
10046 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, DAG.getUNDEF(ResVT),
10047 Op.getOperand(0), DAG.getVectorIdxConstant(0, dl));
10048 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10049 DAG.getVectorIdxConstant(NumElems / 2, dl));
10050}
10051
10053 const X86Subtarget &Subtarget,
10054 SelectionDAG &DAG) {
10055 SDLoc DL(Op);
10056 MVT VT = Op.getSimpleValueType();
10057 if (VT.getVectorElementType() == MVT::i1)
10058 return LowerCONCAT_VECTORSvXi1(Op, DL, Subtarget, DAG);
10059
10060 // AVX can use the vinsertf128 instruction to create 256-bit vectors
10061 // from two other 128-bit ones.
10062 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10063 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10064 (VT.is512BitVector() &&
10065 (Op.getNumOperands() == 2 || Op.getNumOperands() == 4)));
10066 return LowerAVXCONCAT_VECTORS(Op, DL, DAG, Subtarget);
10067}
10068
10069//===----------------------------------------------------------------------===//
10070// Vector shuffle lowering
10071//
10072// This is an experimental code path for lowering vector shuffles on x86. It is
10073// designed to handle arbitrary vector shuffles and blends, gracefully
10074// degrading performance as necessary. It works hard to recognize idiomatic
10075// shuffles and lower them to optimal instruction patterns without leaving
10076// a framework that allows reasonably efficient handling of all vector shuffle
10077// patterns.
10078//===----------------------------------------------------------------------===//
10079
10080/// Checks whether the vector elements referenced by two shuffle masks are
10081/// equivalent.
10082static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
10083 int Idx, int ExpectedIdx) {
10084 assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
10085 ExpectedIdx < MaskSize && "Out of range element index");
10086 if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
10087 return false;
10088
10089 EVT VT = Op.getValueType();
10090 EVT ExpectedVT = ExpectedOp.getValueType();
10091
10092 // Sources must be vectors and match the mask's element count.
10093 if (!VT.isVector() || !ExpectedVT.isVector() ||
10094 (int)VT.getVectorNumElements() != MaskSize ||
10095 (int)ExpectedVT.getVectorNumElements() != MaskSize)
10096 return false;
10097
10098 // Exact match.
10099 if (Idx == ExpectedIdx && Op == ExpectedOp)
10100 return true;
10101
10102 switch (Op.getOpcode()) {
10103 case ISD::BUILD_VECTOR:
10104 // If the values are build vectors, we can look through them to find
10105 // equivalent inputs that make the shuffles equivalent.
10106 return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
10107 case ISD::BITCAST: {
10109 EVT SrcVT = Src.getValueType();
10110 if (Op == ExpectedOp && SrcVT.isVector()) {
10111 if ((SrcVT.getScalarSizeInBits() % VT.getScalarSizeInBits()) == 0) {
10112 unsigned Scale = SrcVT.getScalarSizeInBits() / VT.getScalarSizeInBits();
10113 return (Idx % Scale) == (ExpectedIdx % Scale) &&
10114 IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10115 Idx / Scale, ExpectedIdx / Scale);
10116 }
10117 if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0) {
10118 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
10119 for (unsigned I = 0; I != Scale; ++I)
10120 if (!IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10121 (Idx * Scale) + I,
10122 (ExpectedIdx * Scale) + I))
10123 return false;
10124 return true;
10125 }
10126 }
10127 break;
10128 }
10129 case ISD::VECTOR_SHUFFLE: {
10130 auto *SVN = cast<ShuffleVectorSDNode>(Op);
10131 return Op == ExpectedOp &&
10132 SVN->getMaskElt(Idx) == SVN->getMaskElt(ExpectedIdx);
10133 }
10134 case X86ISD::VBROADCAST:
10135 case X86ISD::VBROADCAST_LOAD:
10136 return Op == ExpectedOp;
10137 case X86ISD::SUBV_BROADCAST_LOAD:
10138 if (Op == ExpectedOp) {
10139 auto *MemOp = cast<MemSDNode>(Op);
10140 unsigned NumMemElts = MemOp->getMemoryVT().getVectorNumElements();
10141 return (Idx % NumMemElts) == (ExpectedIdx % NumMemElts);
10142 }
10143 break;
10144 case X86ISD::VPERMI: {
10145 if (Op == ExpectedOp) {
10147 DecodeVPERMMask(MaskSize, Op.getConstantOperandVal(1), Mask);
10148 SDValue Src = Op.getOperand(0);
10149 return IsElementEquivalent(MaskSize, Src, Src, Mask[Idx],
10150 Mask[ExpectedIdx]);
10151 }
10152 break;
10153 }
10154 case X86ISD::HADD:
10155 case X86ISD::HSUB:
10156 case X86ISD::FHADD:
10157 case X86ISD::FHSUB:
10158 case X86ISD::PACKSS:
10159 case X86ISD::PACKUS:
10160 // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
10161 // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
10162 if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
10163 int NumElts = VT.getVectorNumElements();
10164 int NumLanes = VT.getSizeInBits() / 128;
10165 int NumEltsPerLane = NumElts / NumLanes;
10166 int NumHalfEltsPerLane = NumEltsPerLane / 2;
10167 bool SameLane = (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
10168 bool SameElt =
10169 (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
10170 return SameLane && SameElt;
10171 }
10172 break;
10173 }
10174
10175 return false;
10176}
10177
10178/// Tiny helper function to identify a no-op mask.
10179///
10180/// This is a somewhat boring predicate function. It checks whether the mask
10181/// array input, which is assumed to be a single-input shuffle mask of the kind
10182/// used by the X86 shuffle instructions (not a fully general
10183/// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10184/// in-place shuffle are 'no-op's.
10186 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10187 assert(Mask[i] >= -1 && "Out of bound mask element!");
10188 if (Mask[i] >= 0 && Mask[i] != i)
10189 return false;
10190 }
10191 return true;
10192}
10193
10194/// Test whether there are elements crossing LaneSizeInBits lanes in this
10195/// shuffle mask.
10196///
10197/// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10198/// and we routinely test for these.
10199static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10200 unsigned ScalarSizeInBits,
10201 ArrayRef<int> Mask) {
10202 assert(LaneSizeInBits && ScalarSizeInBits &&
10203 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10204 "Illegal shuffle lane size");
10205 int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10206 int Size = Mask.size();
10207 for (int i = 0; i < Size; ++i)
10208 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10209 return true;
10210 return false;
10211}
10212
10213/// Test whether there are elements crossing 128-bit lanes in this
10214/// shuffle mask.
10216 return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10217}
10218
10219/// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
10220/// from multiple lanes - this is different to isLaneCrossingShuffleMask to
10221/// better support 'repeated mask + lane permute' style shuffles.
10222static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
10223 unsigned ScalarSizeInBits,
10224 ArrayRef<int> Mask) {
10225 assert(LaneSizeInBits && ScalarSizeInBits &&
10226 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10227 "Illegal shuffle lane size");
10228 int NumElts = Mask.size();
10229 int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
10230 int NumLanes = NumElts / NumEltsPerLane;
10231 if (NumLanes > 1) {
10232 for (int i = 0; i != NumLanes; ++i) {
10233 int SrcLane = -1;
10234 for (int j = 0; j != NumEltsPerLane; ++j) {
10235 int M = Mask[(i * NumEltsPerLane) + j];
10236 if (M < 0)
10237 continue;
10238 int Lane = (M % NumElts) / NumEltsPerLane;
10239 if (SrcLane >= 0 && SrcLane != Lane)
10240 return true;
10241 SrcLane = Lane;
10242 }
10243 }
10244 }
10245 return false;
10246}
10247
10248/// Test whether a shuffle mask is equivalent within each sub-lane.
10249///
10250/// This checks a shuffle mask to see if it is performing the same
10251/// lane-relative shuffle in each sub-lane. This trivially implies
10252/// that it is also not lane-crossing. It may however involve a blend from the
10253/// same lane of a second vector.
10254///
10255/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10256/// non-trivial to compute in the face of undef lanes. The representation is
10257/// suitable for use with existing 128-bit shuffles as entries from the second
10258/// vector have been remapped to [LaneSize, 2*LaneSize).
10259static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10260 ArrayRef<int> Mask,
10261 SmallVectorImpl<int> &RepeatedMask) {
10262 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10263 RepeatedMask.assign(LaneSize, -1);
10264 int Size = Mask.size();
10265 for (int i = 0; i < Size; ++i) {
10266 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10267 if (Mask[i] < 0)
10268 continue;
10269 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10270 // This entry crosses lanes, so there is no way to model this shuffle.
10271 return false;
10272
10273 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10274 // Adjust second vector indices to start at LaneSize instead of Size.
10275 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10276 : Mask[i] % LaneSize + LaneSize;
10277 if (RepeatedMask[i % LaneSize] < 0)
10278 // This is the first non-undef entry in this slot of a 128-bit lane.
10279 RepeatedMask[i % LaneSize] = LocalM;
10280 else if (RepeatedMask[i % LaneSize] != LocalM)
10281 // Found a mismatch with the repeated mask.
10282 return false;
10283 }
10284 return true;
10285}
10286
10287/// Test whether a shuffle mask is equivalent within each 128-bit lane.
10288static bool
10290 SmallVectorImpl<int> &RepeatedMask) {
10291 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10292}
10293
10294static bool
10296 SmallVector<int, 32> RepeatedMask;
10297 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10298}
10299
10300/// Test whether a shuffle mask is equivalent within each 256-bit lane.
10301static bool
10303 SmallVectorImpl<int> &RepeatedMask) {
10304 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10305}
10306
10307/// Test whether a target shuffle mask is equivalent within each sub-lane.
10308/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10309static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
10310 unsigned EltSizeInBits,
10311 ArrayRef<int> Mask,
10312 SmallVectorImpl<int> &RepeatedMask) {
10313 int LaneSize = LaneSizeInBits / EltSizeInBits;
10314 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10315 int Size = Mask.size();
10316 for (int i = 0; i < Size; ++i) {
10317 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10318 if (Mask[i] == SM_SentinelUndef)
10319 continue;
10320 if (Mask[i] == SM_SentinelZero) {
10321 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10322 return false;
10323 RepeatedMask[i % LaneSize] = SM_SentinelZero;
10324 continue;
10325 }
10326 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10327 // This entry crosses lanes, so there is no way to model this shuffle.
10328 return false;
10329
10330 // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
10331 // later vector indices to start at multiples of LaneSize instead of Size.
10332 int LaneM = Mask[i] / Size;
10333 int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
10334 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10335 // This is the first non-undef entry in this slot of a 128-bit lane.
10336 RepeatedMask[i % LaneSize] = LocalM;
10337 else if (RepeatedMask[i % LaneSize] != LocalM)
10338 // Found a mismatch with the repeated mask.
10339 return false;
10340 }
10341 return true;
10342}
10343
10344/// Test whether a target shuffle mask is equivalent within each sub-lane.
10345/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10346static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10347 ArrayRef<int> Mask,
10348 SmallVectorImpl<int> &RepeatedMask) {
10349 return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
10350 Mask, RepeatedMask);
10351}
10352
10353/// Checks whether a shuffle mask is equivalent to an explicit list of
10354/// arguments.
10355///
10356/// This is a fast way to test a shuffle mask against a fixed pattern:
10357///
10358/// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
10359///
10360/// It returns true if the mask is exactly as wide as the argument list, and
10361/// each element of the mask is either -1 (signifying undef) or the value given
10362/// in the argument.
10363static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
10364 SDValue V1 = SDValue(),
10365 SDValue V2 = SDValue()) {
10366 int Size = Mask.size();
10367 if (Size != (int)ExpectedMask.size())
10368 return false;
10369
10370 for (int i = 0; i < Size; ++i) {
10371 assert(Mask[i] >= -1 && "Out of bound mask element!");
10372 int MaskIdx = Mask[i];
10373 int ExpectedIdx = ExpectedMask[i];
10374 if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
10375 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10376 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10377 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10378 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10379 if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10380 return false;
10381 }
10382 }
10383 return true;
10384}
10385
10386/// Checks whether a target shuffle mask is equivalent to an explicit pattern.
10387///
10388/// The masks must be exactly the same width.
10389///
10390/// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
10391/// value in ExpectedMask is always accepted. Otherwise the indices must match.
10392///
10393/// SM_SentinelZero is accepted as a valid negative index but must match in
10394/// both, or via a known bits test.
10396 ArrayRef<int> ExpectedMask,
10397 const SelectionDAG &DAG,
10398 SDValue V1 = SDValue(),
10399 SDValue V2 = SDValue()) {
10400 int Size = Mask.size();
10401 if (Size != (int)ExpectedMask.size())
10402 return false;
10403 assert(llvm::all_of(ExpectedMask,
10404 [Size](int M) {
10405 return M == SM_SentinelZero ||
10406 isInRange(M, 0, 2 * Size);
10407 }) &&
10408 "Illegal target shuffle mask");
10409
10410 // Check for out-of-range target shuffle mask indices.
10411 if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
10412 return false;
10413
10414 // Don't use V1/V2 if they're not the same size as the shuffle mask type.
10415 if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
10416 !V1.getValueType().isVector()))
10417 V1 = SDValue();
10418 if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
10419 !V2.getValueType().isVector()))
10420 V2 = SDValue();
10421
10422 APInt ZeroV1 = APInt::getZero(Size);
10423 APInt ZeroV2 = APInt::getZero(Size);
10424
10425 for (int i = 0; i < Size; ++i) {
10426 int MaskIdx = Mask[i];
10427 int ExpectedIdx = ExpectedMask[i];
10428 if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
10429 continue;
10430 // If we failed to match an expected SM_SentinelZero then early out.
10431 if (ExpectedIdx < 0)
10432 return false;
10433 if (MaskIdx == SM_SentinelZero) {
10434 // If we need this expected index to be a zero element, then update the
10435 // relevant zero mask and perform the known bits at the end to minimize
10436 // repeated computes.
10437 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10438 if (ExpectedV &&
10439 Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
10440 int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10441 APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
10442 ZeroMask.setBit(BitIdx);
10443 continue;
10444 }
10445 }
10446 if (MaskIdx >= 0) {
10447 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10448 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10449 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10450 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10451 if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10452 continue;
10453 }
10454 return false;
10455 }
10456 return (ZeroV1.isZero() ||
10457 (DAG.MaskedVectorIsZero(V1, ZeroV1) &&
10458 DAG.isGuaranteedNotToBeUndefOrPoison(V1, ZeroV1))) &&
10459 (ZeroV2.isZero() ||
10460 (DAG.MaskedVectorIsZero(V2, ZeroV2) &&
10461 DAG.isGuaranteedNotToBeUndefOrPoison(V2, ZeroV2)));
10462}
10463
10464// Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
10465// instructions.
10467 const SelectionDAG &DAG) {
10468 if (VT != MVT::v8i32 && VT != MVT::v8f32)
10469 return false;
10470
10471 SmallVector<int, 8> Unpcklwd;
10472 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
10473 /* Unary = */ false);
10474 SmallVector<int, 8> Unpckhwd;
10475 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
10476 /* Unary = */ false);
10477 bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
10478 isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
10479 return IsUnpackwdMask;
10480}
10481
10483 const SelectionDAG &DAG) {
10484 // Create 128-bit vector type based on mask size.
10485 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
10486 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
10487
10488 // We can't assume a canonical shuffle mask, so try the commuted version too.
10489 SmallVector<int, 4> CommutedMask(Mask);
10491
10492 // Match any of unary/binary or low/high.
10493 for (unsigned i = 0; i != 4; ++i) {
10494 SmallVector<int, 16> UnpackMask;
10495 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
10496 if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
10497 isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
10498 return true;
10499 }
10500 return false;
10501}
10502
10503/// Return true if a shuffle mask chooses elements identically in its top and
10504/// bottom halves. For example, any splat mask has the same top and bottom
10505/// halves. If an element is undefined in only one half of the mask, the halves
10506/// are not considered identical.
10508 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
10509 unsigned HalfSize = Mask.size() / 2;
10510 for (unsigned i = 0; i != HalfSize; ++i) {
10511 if (Mask[i] != Mask[i + HalfSize])
10512 return false;
10513 }
10514 return true;
10515}
10516
10517/// Get a 4-lane 8-bit shuffle immediate for a mask.
10518///
10519/// This helper function produces an 8-bit shuffle immediate corresponding to
10520/// the ubiquitous shuffle encoding scheme used in x86 instructions for
10521/// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10522/// example.
10523///
10524/// NB: We rely heavily on "undef" masks preserving the input lane.
10525static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10526 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
10527 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
10528 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
10529 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
10530 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
10531
10532 // If the mask only uses one non-undef element, then fully 'splat' it to
10533 // improve later broadcast matching.
10534 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10535 assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
10536
10537 int FirstElt = Mask[FirstIndex];
10538 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
10539 return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
10540
10541 unsigned Imm = 0;
10542 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10543 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10544 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10545 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10546 return Imm;
10547}
10548
10550 SelectionDAG &DAG) {
10551 return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10552}
10553
10554// Canonicalize SHUFPD mask to improve chances of further folding.
10555// Mask elements are assumed to be -1, 0 or 1 to match the SHUFPD lo/hi pattern.
10556static unsigned getSHUFPDImm(ArrayRef<int> Mask) {
10557 assert((Mask.size() == 2 || Mask.size() == 4 || Mask.size() == 8) &&
10558 "Unexpected SHUFPD mask size");
10559 assert(all_of(Mask, [](int M) { return -1 <= M && M <= 1; }) &&
10560 "Unexpected SHUFPD mask elements");
10561
10562 // If the mask only uses one non-undef element, then fully 'splat' it to
10563 // improve later broadcast matching.
10564 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10565 assert(0 <= FirstIndex && FirstIndex < (int)Mask.size() &&
10566 "All undef shuffle mask");
10567
10568 int FirstElt = Mask[FirstIndex];
10569 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }) &&
10570 count_if(Mask, [FirstElt](int M) { return M == FirstElt; }) > 1) {
10571 unsigned Imm = 0;
10572 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10573 Imm |= FirstElt << I;
10574 return Imm;
10575 }
10576
10577 // Attempt to keep any undef elements in place to improve chances of the
10578 // shuffle becoming a (commutative) blend.
10579 unsigned Imm = 0;
10580 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10581 Imm |= (Mask[I] < 0 ? (I & 1) : Mask[I]) << I;
10582
10583 return Imm;
10584}
10585
10587 SelectionDAG &DAG) {
10588 return DAG.getTargetConstant(getSHUFPDImm(Mask), DL, MVT::i8);
10589}
10590
10591// The Shuffle result is as follow:
10592// 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10593// Each Zeroable's element correspond to a particular Mask's element.
10594// As described in computeZeroableShuffleElements function.
10595//
10596// The function looks for a sub-mask that the nonzero elements are in
10597// increasing order. If such sub-mask exist. The function returns true.
10598static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10599 ArrayRef<int> Mask, const EVT &VectorType,
10600 bool &IsZeroSideLeft) {
10601 int NextElement = -1;
10602 // Check if the Mask's nonzero elements are in increasing order.
10603 for (int i = 0, e = Mask.size(); i < e; i++) {
10604 // Checks if the mask's zeros elements are built from only zeros.
10605 assert(Mask[i] >= -1 && "Out of bound mask element!");
10606 if (Mask[i] < 0)
10607 return false;
10608 if (Zeroable[i])
10609 continue;
10610 // Find the lowest non zero element
10611 if (NextElement < 0) {
10612 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10613 IsZeroSideLeft = NextElement != 0;
10614 }
10615 // Exit if the mask's non zero elements are not in increasing order.
10616 if (NextElement != Mask[i])
10617 return false;
10618 NextElement++;
10619 }
10620 return true;
10621}
10622
10623static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
10625 const X86Subtarget &Subtarget,
10626 unsigned Depth = 0);
10627
10628/// Try to lower a shuffle with a single PSHUFB of V1 or V2.
10630 ArrayRef<int> Mask, SDValue V1,
10631 SDValue V2, const APInt &Zeroable,
10632 const X86Subtarget &Subtarget,
10633 SelectionDAG &DAG) {
10634 int Size = Mask.size();
10635 int LaneSize = 128 / VT.getScalarSizeInBits();
10636 const int NumBytes = VT.getSizeInBits() / 8;
10637 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10638
10639 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
10640 (Subtarget.hasAVX2() && VT.is256BitVector()) ||
10641 (Subtarget.hasBWI() && VT.is512BitVector()));
10642
10643 SmallVector<int, 64> PSHUFBMask(NumBytes, -1);
10644 SDValue V;
10645 for (int i = 0; i < NumBytes; ++i) {
10646 int M = Mask[i / NumEltBytes];
10647 if (M < 0)
10648 continue;
10649
10650 if (Zeroable[i / NumEltBytes]) {
10651 // Sign bit set in i8 mask means zero element.
10652 PSHUFBMask[i] = 0x80;
10653 continue;
10654 }
10655
10656 // We can only use a single input of V1 or V2.
10657 SDValue SrcV = (M >= Size ? V2 : V1);
10658 if (V && V != SrcV)
10659 return SDValue();
10660 V = SrcV;
10661 M %= Size;
10662
10663 // PSHUFB can't cross lanes, ensure this doesn't happen.
10664 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10665 return SDValue();
10666
10667 M = M % LaneSize;
10668 M = M * NumEltBytes + (i % NumEltBytes);
10669 PSHUFBMask[i] = M;
10670 }
10671 assert(V && "Failed to find a source input");
10672
10673 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10674 SDValue R = getConstVector(PSHUFBMask, I8VT, DAG, DL, /*IsMask=*/true);
10675 R = DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V), R);
10676 return DAG.getBitcast(VT, R);
10677}
10678
10679/// Return Mask with the necessary casting or extending
10680/// for \p Mask according to \p MaskVT when lowering masking intrinsics
10681static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10682 const X86Subtarget &Subtarget, SelectionDAG &DAG,
10683 const SDLoc &dl) {
10684 MVT SrcVT = Mask.getSimpleValueType();
10685 assert(SrcVT.isScalarInteger() && "Expected scalar integer mask source!");
10686 assert(MaskVT.bitsLE(SrcVT) && "Unexpected mask size!");
10687 assert(MaskVT.getVectorElementType() == MVT::i1 && "Bool vector expected!");
10688
10689 if (isAllOnesConstant(Mask))
10690 return DAG.getConstant(1, dl, MaskVT);
10691 if (X86::isZeroNode(Mask))
10692 return DAG.getConstant(0, dl, MaskVT);
10693
10694 // Attempt to pre-truncate the mask source (to a minimum of i8).
10695 if (SrcVT.getSizeInBits() > MaskVT.getVectorNumElements()) {
10696 SrcVT = MVT::getIntegerVT(std::max((int)MaskVT.getVectorNumElements(), 8));
10697 Mask = DAG.getNode(ISD::TRUNCATE, dl, SrcVT, Mask);
10698 }
10699
10700 if (SrcVT == MVT::i64 && Subtarget.is32Bit()) {
10701 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
10702 assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
10703 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
10704 SDValue Lo, Hi;
10705 std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
10706 Lo = DAG.getBitcast(MVT::v32i1, Lo);
10707 Hi = DAG.getBitcast(MVT::v32i1, Hi);
10708 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
10709 }
10710
10711 MVT BitcastVT = MVT::getVectorVT(MVT::i1, SrcVT.getSizeInBits());
10712 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
10713 // are extracted by EXTRACT_SUBVECTOR.
10714 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
10715 DAG.getBitcast(BitcastVT, Mask),
10716 DAG.getVectorIdxConstant(0, dl));
10717}
10718
10719// X86 has dedicated shuffle that can be lowered to VEXPAND
10721 SDValue V2, ArrayRef<int> Mask,
10722 const APInt &Zeroable,
10723 const X86Subtarget &Subtarget,
10724 SelectionDAG &DAG) {
10725 bool IsLeftZeroSide = true;
10726 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10727 IsLeftZeroSide))
10728 return SDValue();
10729 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10731 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10732 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10733 unsigned NumElts = VT.getVectorNumElements();
10734 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
10735 "Unexpected number of vector elements");
10736 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10737 Subtarget, DAG, DL);
10738 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10739 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10740 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10741}
10742
10744 unsigned &UnpackOpcode, bool IsUnary,
10745 ArrayRef<int> TargetMask, const SDLoc &DL,
10746 SelectionDAG &DAG,
10747 const X86Subtarget &Subtarget) {
10748 int NumElts = VT.getVectorNumElements();
10749
10750 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10751 for (int i = 0; i != NumElts; i += 2) {
10752 int M1 = TargetMask[i + 0];
10753 int M2 = TargetMask[i + 1];
10754 Undef1 &= (SM_SentinelUndef == M1);
10755 Undef2 &= (SM_SentinelUndef == M2);
10756 Zero1 &= isUndefOrZero(M1);
10757 Zero2 &= isUndefOrZero(M2);
10758 }
10759 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
10760 "Zeroable shuffle detected");
10761
10762 // Attempt to match the target mask against the unpack lo/hi mask patterns.
10763 SmallVector<int, 64> Unpckl, Unpckh;
10764 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10765 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
10766 (IsUnary ? V1 : V2))) {
10767 UnpackOpcode = X86ISD::UNPCKL;
10768 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10769 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10770 return true;
10771 }
10772
10773 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10774 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
10775 (IsUnary ? V1 : V2))) {
10776 UnpackOpcode = X86ISD::UNPCKH;
10777 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10778 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10779 return true;
10780 }
10781
10782 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10783 if (IsUnary && (Zero1 || Zero2)) {
10784 // Don't bother if we can blend instead.
10785 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10786 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10787 return false;
10788
10789 bool MatchLo = true, MatchHi = true;
10790 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10791 int M = TargetMask[i];
10792
10793 // Ignore if the input is known to be zero or the index is undef.
10794 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10795 (M == SM_SentinelUndef))
10796 continue;
10797
10798 MatchLo &= (M == Unpckl[i]);
10799 MatchHi &= (M == Unpckh[i]);
10800 }
10801
10802 if (MatchLo || MatchHi) {
10803 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10804 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10805 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10806 return true;
10807 }
10808 }
10809
10810 // If a binary shuffle, commute and try again.
10811 if (!IsUnary) {
10813 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
10814 UnpackOpcode = X86ISD::UNPCKL;
10815 std::swap(V1, V2);
10816 return true;
10817 }
10818
10820 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
10821 UnpackOpcode = X86ISD::UNPCKH;
10822 std::swap(V1, V2);
10823 return true;
10824 }
10825 }
10826
10827 return false;
10828}
10829
10830// X86 has dedicated unpack instructions that can handle specific blend
10831// operations: UNPCKH and UNPCKL.
10833 SDValue V2, ArrayRef<int> Mask,
10834 SelectionDAG &DAG) {
10835 SmallVector<int, 8> Unpckl;
10836 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10837 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10838 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10839
10840 SmallVector<int, 8> Unpckh;
10841 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10842 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10843 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10844
10845 // Commute and try again.
10847 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10848 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10849
10851 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10852 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10853
10854 return SDValue();
10855}
10856
10857/// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
10858/// followed by unpack 256-bit.
10860 SDValue V2, ArrayRef<int> Mask,
10861 SelectionDAG &DAG) {
10862 SmallVector<int, 32> Unpckl, Unpckh;
10863 createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
10864 createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
10865
10866 unsigned UnpackOpcode;
10867 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10868 UnpackOpcode = X86ISD::UNPCKL;
10869 else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10870 UnpackOpcode = X86ISD::UNPCKH;
10871 else
10872 return SDValue();
10873
10874 // This is a "natural" unpack operation (rather than the 128-bit sectored
10875 // operation implemented by AVX). We need to rearrange 64-bit chunks of the
10876 // input in order to use the x86 instruction.
10877 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
10878 DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
10879 V1 = DAG.getBitcast(VT, V1);
10880 return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
10881}
10882
10883// Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
10884// source into the lower elements and zeroing the upper elements.
10885static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
10886 ArrayRef<int> Mask, const APInt &Zeroable,
10887 const X86Subtarget &Subtarget) {
10888 if (!VT.is512BitVector() && !Subtarget.hasVLX())
10889 return false;
10890
10891 unsigned NumElts = Mask.size();
10892 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10893 unsigned MaxScale = 64 / EltSizeInBits;
10894
10895 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10896 unsigned SrcEltBits = EltSizeInBits * Scale;
10897 if (SrcEltBits < 32 && !Subtarget.hasBWI())
10898 continue;
10899 unsigned NumSrcElts = NumElts / Scale;
10900 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
10901 continue;
10902 unsigned UpperElts = NumElts - NumSrcElts;
10903 if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10904 continue;
10905 SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
10906 SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
10907 DstVT = MVT::getIntegerVT(EltSizeInBits);
10908 if ((NumSrcElts * EltSizeInBits) >= 128) {
10909 // ISD::TRUNCATE
10910 DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
10911 } else {
10912 // X86ISD::VTRUNC
10913 DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
10914 }
10915 return true;
10916 }
10917
10918 return false;
10919}
10920
10921// Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
10922// element padding to the final DstVT.
10923static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
10924 const X86Subtarget &Subtarget,
10925 SelectionDAG &DAG, bool ZeroUppers) {
10926 MVT SrcVT = Src.getSimpleValueType();
10927 MVT DstSVT = DstVT.getScalarType();
10928 unsigned NumDstElts = DstVT.getVectorNumElements();
10929 unsigned NumSrcElts = SrcVT.getVectorNumElements();
10930 unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
10931
10932 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
10933 return SDValue();
10934
10935 // Perform a direct ISD::TRUNCATE if possible.
10936 if (NumSrcElts == NumDstElts)
10937 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
10938
10939 if (NumSrcElts > NumDstElts) {
10940 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10941 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10942 return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
10943 }
10944
10945 if ((NumSrcElts * DstEltSizeInBits) >= 128) {
10946 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10947 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10948 return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10949 DstVT.getSizeInBits());
10950 }
10951
10952 // Non-VLX targets must truncate from a 512-bit type, so we need to
10953 // widen, truncate and then possibly extract the original subvector.
10954 if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
10955 SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
10956 return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
10957 }
10958
10959 // Fallback to a X86ISD::VTRUNC, padding if necessary.
10960 MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
10961 SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
10962 if (DstVT != TruncVT)
10963 Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10964 DstVT.getSizeInBits());
10965 return Trunc;
10966}
10967
10968// Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10969//
10970// An example is the following:
10971//
10972// t0: ch = EntryToken
10973// t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10974// t25: v4i32 = truncate t2
10975// t41: v8i16 = bitcast t25
10976// t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10977// Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10978// t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10979// t18: v2i64 = bitcast t51
10980//
10981// One can just use a single vpmovdw instruction, without avx512vl we need to
10982// use the zmm variant and extract the lower subvector, padding with zeroes.
10983// TODO: Merge with lowerShuffleAsVTRUNC.
10985 SDValue V2, ArrayRef<int> Mask,
10986 const APInt &Zeroable,
10987 const X86Subtarget &Subtarget,
10988 SelectionDAG &DAG) {
10989 assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
10990 if (!Subtarget.hasAVX512())
10991 return SDValue();
10992
10993 unsigned NumElts = VT.getVectorNumElements();
10994 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10995 unsigned MaxScale = 64 / EltSizeInBits;
10996 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10997 unsigned SrcEltBits = EltSizeInBits * Scale;
10998 unsigned NumSrcElts = NumElts / Scale;
10999 unsigned UpperElts = NumElts - NumSrcElts;
11000 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11001 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11002 continue;
11003
11004 // Attempt to find a matching source truncation, but as a fall back VLX
11005 // cases can use the VPMOV directly.
11007 if (Src.getOpcode() == ISD::TRUNCATE &&
11008 Src.getScalarValueSizeInBits() == SrcEltBits) {
11009 Src = Src.getOperand(0);
11010 } else if (Subtarget.hasVLX()) {
11011 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11012 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11013 Src = DAG.getBitcast(SrcVT, Src);
11014 // Don't do this if PACKSS/PACKUS could perform it cheaper.
11015 if (Scale == 2 &&
11016 ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
11017 (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
11018 return SDValue();
11019 } else
11020 return SDValue();
11021
11022 // VPMOVWB is only available with avx512bw.
11023 if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
11024 return SDValue();
11025
11026 bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
11027 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11028 }
11029
11030 return SDValue();
11031}
11032
11033// Attempt to match binary shuffle patterns as a truncate.
11035 SDValue V2, ArrayRef<int> Mask,
11036 const APInt &Zeroable,
11037 const X86Subtarget &Subtarget,
11038 SelectionDAG &DAG) {
11039 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11040 "Unexpected VTRUNC type");
11041 if (!Subtarget.hasAVX512() ||
11042 (VT.is256BitVector() && !Subtarget.useAVX512Regs()))
11043 return SDValue();
11044
11045 unsigned NumElts = VT.getVectorNumElements();
11046 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11047 unsigned MaxScale = 64 / EltSizeInBits;
11048 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11049 // TODO: Support non-BWI VPMOVWB truncations?
11050 unsigned SrcEltBits = EltSizeInBits * Scale;
11051 if (SrcEltBits < 32 && !Subtarget.hasBWI())
11052 continue;
11053
11054 // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
11055 // Bail if the V2 elements are undef.
11056 unsigned NumHalfSrcElts = NumElts / Scale;
11057 unsigned NumSrcElts = 2 * NumHalfSrcElts;
11058 for (unsigned Offset = 0; Offset != Scale; ++Offset) {
11059 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
11060 isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
11061 continue;
11062
11063 // The elements beyond the truncation must be undef/zero.
11064 unsigned UpperElts = NumElts - NumSrcElts;
11065 if (UpperElts > 0 &&
11066 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11067 continue;
11068 bool UndefUppers =
11069 UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
11070
11071 // As we're using both sources then we need to concat them together
11072 // and truncate from the double-sized src.
11073 MVT ConcatVT = VT.getDoubleNumVectorElementsVT();
11074
11075 // For offset truncations, ensure that the concat is cheap.
11076 SDValue Src =
11077 combineConcatVectorOps(DL, ConcatVT, {V1, V2}, DAG, Subtarget);
11078 if (!Src) {
11079 if (Offset)
11080 continue;
11081 Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
11082 }
11083
11084 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11085 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11086 Src = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, SrcVT, Src,
11087 Offset * EltSizeInBits, DAG);
11088 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11089 }
11090 }
11091
11092 return SDValue();
11093}
11094
11095/// Check whether a compaction lowering can be done by dropping even/odd
11096/// elements and compute how many times even/odd elements must be dropped.
11097///
11098/// This handles shuffles which take every Nth element where N is a power of
11099/// two. Example shuffle masks:
11100///
11101/// (even)
11102/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
11103/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11104/// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
11105/// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
11106/// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
11107/// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
11108///
11109/// (odd)
11110/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 14
11111/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
11112///
11113/// Any of these lanes can of course be undef.
11114///
11115/// This routine only supports N <= 3.
11116/// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11117/// for larger N.
11118///
11119/// \returns N above, or the number of times even/odd elements must be dropped
11120/// if there is such a number. Otherwise returns zero.
11121static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
11122 bool IsSingleInput) {
11123 // The modulus for the shuffle vector entries is based on whether this is
11124 // a single input or not.
11125 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11126 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
11127 "We should only be called with masks with a power-of-2 size!");
11128
11129 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11130 int Offset = MatchEven ? 0 : 1;
11131
11132 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11133 // and 2^3 simultaneously. This is because we may have ambiguity with
11134 // partially undef inputs.
11135 bool ViableForN[3] = {true, true, true};
11136
11137 for (int i = 0, e = Mask.size(); i < e; ++i) {
11138 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11139 // want.
11140 if (Mask[i] < 0)
11141 continue;
11142
11143 bool IsAnyViable = false;
11144 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11145 if (ViableForN[j]) {
11146 uint64_t N = j + 1;
11147
11148 // The shuffle mask must be equal to (i * 2^N) % M.
11149 if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
11150 IsAnyViable = true;
11151 else
11152 ViableForN[j] = false;
11153 }
11154 // Early exit if we exhaust the possible powers of two.
11155 if (!IsAnyViable)
11156 break;
11157 }
11158
11159 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11160 if (ViableForN[j])
11161 return j + 1;
11162
11163 // Return 0 as there is no viable power of two.
11164 return 0;
11165}
11166
11167// X86 has dedicated pack instructions that can handle specific truncation
11168// operations: PACKSS and PACKUS.
11169// Checks for compaction shuffle masks if MaxStages > 1.
11170// TODO: Add support for matching multiple PACKSS/PACKUS stages.
11171static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11172 unsigned &PackOpcode, ArrayRef<int> TargetMask,
11173 const SelectionDAG &DAG,
11174 const X86Subtarget &Subtarget,
11175 unsigned MaxStages = 1) {
11176 unsigned NumElts = VT.getVectorNumElements();
11177 unsigned BitSize = VT.getScalarSizeInBits();
11178 assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
11179 "Illegal maximum compaction");
11180
11181 auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11182 unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11183 unsigned NumPackedBits = NumSrcBits - BitSize;
11184 N1 = peekThroughBitcasts(N1);
11185 N2 = peekThroughBitcasts(N2);
11186 unsigned NumBits1 = N1.getScalarValueSizeInBits();
11187 unsigned NumBits2 = N2.getScalarValueSizeInBits();
11188 bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
11189 bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
11190 if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
11191 (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
11192 return false;
11193 if (Subtarget.hasSSE41() || BitSize == 8) {
11194 APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11195 if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
11196 (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
11197 V1 = N1;
11198 V2 = N2;
11199 SrcVT = PackVT;
11200 PackOpcode = X86ISD::PACKUS;
11201 return true;
11202 }
11203 }
11204 bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
11205 bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
11206 if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
11207 DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
11208 (N2.isUndef() || IsZero2 || IsAllOnes2 ||
11209 DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
11210 V1 = N1;
11211 V2 = N2;
11212 SrcVT = PackVT;
11213 PackOpcode = X86ISD::PACKSS;
11214 return true;
11215 }
11216 return false;
11217 };
11218
11219 // Attempt to match against wider and wider compaction patterns.
11220 for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11221 MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11222 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11223
11224 // Try binary shuffle.
11225 SmallVector<int, 32> BinaryMask;
11226 createPackShuffleMask(VT, BinaryMask, false, NumStages);
11227 if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
11228 if (MatchPACK(V1, V2, PackVT))
11229 return true;
11230
11231 // Try unary shuffle.
11232 SmallVector<int, 32> UnaryMask;
11233 createPackShuffleMask(VT, UnaryMask, true, NumStages);
11234 if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
11235 if (MatchPACK(V1, V1, PackVT))
11236 return true;
11237 }
11238
11239 return false;
11240}
11241
11243 SDValue V2, ArrayRef<int> Mask,
11244 const X86Subtarget &Subtarget,
11245 SelectionDAG &DAG) {
11246 MVT PackVT;
11247 unsigned PackOpcode;
11248 unsigned SizeBits = VT.getSizeInBits();
11249 unsigned EltBits = VT.getScalarSizeInBits();
11250 unsigned MaxStages = Log2_32(64 / EltBits);
11251 if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11252 Subtarget, MaxStages))
11253 return SDValue();
11254
11255 unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11256 unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11257
11258 // Don't lower multi-stage packs on AVX512, truncation is better.
11259 if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11260 return SDValue();
11261
11262 // Pack to the largest type possible:
11263 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11264 unsigned MaxPackBits = 16;
11265 if (CurrentEltBits > 16 &&
11266 (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11267 MaxPackBits = 32;
11268
11269 // Repeatedly pack down to the target size.
11270 SDValue Res;
11271 for (unsigned i = 0; i != NumStages; ++i) {
11272 unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11273 unsigned NumSrcElts = SizeBits / SrcEltBits;
11274 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11275 MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11276 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11277 MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11278 Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11279 DAG.getBitcast(SrcVT, V2));
11280 V1 = V2 = Res;
11281 CurrentEltBits /= 2;
11282 }
11283 assert(Res && Res.getValueType() == VT &&
11284 "Failed to lower compaction shuffle");
11285 return Res;
11286}
11287
11288/// Try to emit a bitmask instruction for a shuffle.
11289///
11290/// This handles cases where we can model a blend exactly as a bitmask due to
11291/// one of the inputs being zeroable.
11293 SDValue V2, ArrayRef<int> Mask,
11294 const APInt &Zeroable, SelectionDAG &DAG) {
11295 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11296 APInt Zero = APInt::getZero(EltSizeInBIts);
11297 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11298
11299 SmallVector<APInt, 16> VMaskOps(Mask.size(), Zero);
11300 SDValue V;
11301 for (int I = 0, Size = Mask.size(); I != Size; ++I) {
11302 if (Zeroable[I])
11303 continue;
11304 if (Mask[I] % Size != I)
11305 return SDValue(); // Not a blend.
11306 if (!V)
11307 V = Mask[I] < Size ? V1 : V2;
11308 else if (V != (Mask[I] < Size ? V1 : V2))
11309 return SDValue(); // Can only let one input through the mask.
11310
11311 VMaskOps[I] = AllOnes;
11312 }
11313 if (!V)
11314 return SDValue(); // No non-zeroable elements!
11315
11316 MVT LogicVT = VT.changeTypeToInteger();
11317 SDValue VMask = getConstVector(VMaskOps, LogicVT, DAG, DL);
11318 V = DAG.getBitcast(LogicVT, V);
11319 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11320 return DAG.getBitcast(VT, And);
11321}
11322
11323/// Try to emit a blend instruction for a shuffle using bit math.
11324///
11325/// This is used as a fallback approach when first class blend instructions are
11326/// unavailable. Currently it is only suitable for integer vectors, but could
11327/// be generalized for floating point vectors if desirable.
11329 SDValue V2, ArrayRef<int> Mask,
11330 SelectionDAG &DAG) {
11331 assert(VT.isInteger() && "Only supports integer vector types!");
11332 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11333 APInt Zero = APInt::getZero(EltSizeInBIts);
11334 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11335 SmallVector<APInt, 16> MaskOps;
11336 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11337 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11338 return SDValue(); // Shuffled input!
11339 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11340 }
11341 SDValue V1Mask = getConstVector(MaskOps, VT, DAG, DL);
11342 return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
11343}
11344
11346 SDValue PreservedSrc,
11347 const X86Subtarget &Subtarget,
11348 SelectionDAG &DAG);
11349
11352 const APInt &Zeroable, bool &ForceV1Zero,
11353 bool &ForceV2Zero, uint64_t &BlendMask) {
11354 bool V1IsZeroOrUndef =
11355 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11356 bool V2IsZeroOrUndef =
11358
11359 BlendMask = 0;
11360 ForceV1Zero = false, ForceV2Zero = false;
11361 assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11362
11363 int NumElts = Mask.size();
11364 int NumLanes = VT.getSizeInBits() / 128;
11365 int NumEltsPerLane = NumElts / NumLanes;
11366 assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
11367
11368 // For 32/64-bit elements, if we only reference one input (plus any undefs),
11369 // then ensure the blend mask part for that lane just references that input.
11370 bool ForceWholeLaneMasks =
11371 VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
11372
11373 // Attempt to generate the binary blend mask. If an input is zero then
11374 // we can use any lane.
11375 for (int Lane = 0; Lane != NumLanes; ++Lane) {
11376 // Keep track of the inputs used per lane.
11377 bool LaneV1InUse = false;
11378 bool LaneV2InUse = false;
11379 uint64_t LaneBlendMask = 0;
11380 for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
11381 int Elt = (Lane * NumEltsPerLane) + LaneElt;
11382 int M = Mask[Elt];
11383 if (M == SM_SentinelUndef)
11384 continue;
11385 if (M == Elt || (0 <= M && M < NumElts &&
11386 IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
11387 Mask[Elt] = Elt;
11388 LaneV1InUse = true;
11389 continue;
11390 }
11391 if (M == (Elt + NumElts) ||
11392 (NumElts <= M &&
11393 IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
11394 LaneBlendMask |= 1ull << LaneElt;
11395 Mask[Elt] = Elt + NumElts;
11396 LaneV2InUse = true;
11397 continue;
11398 }
11399 if (Zeroable[Elt]) {
11400 if (V1IsZeroOrUndef) {
11401 ForceV1Zero = true;
11402 Mask[Elt] = Elt;
11403 LaneV1InUse = true;
11404 continue;
11405 }
11406 if (V2IsZeroOrUndef) {
11407 ForceV2Zero = true;
11408 LaneBlendMask |= 1ull << LaneElt;
11409 Mask[Elt] = Elt + NumElts;
11410 LaneV2InUse = true;
11411 continue;
11412 }
11413 }
11414 return false;
11415 }
11416
11417 // If we only used V2 then splat the lane blend mask to avoid any demanded
11418 // elts from V1 in this lane (the V1 equivalent is implicit with a zero
11419 // blend mask bit).
11420 if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
11421 LaneBlendMask = (1ull << NumEltsPerLane) - 1;
11422
11423 BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
11424 }
11425 return true;
11426}
11427
11428/// Try to emit a blend instruction for a shuffle.
11429///
11430/// This doesn't do any checks for the availability of instructions for blending
11431/// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11432/// be matched in the backend with the type given. What it does check for is
11433/// that the shuffle mask is a blend, or convertible into a blend with zero.
11435 SDValue V2, ArrayRef<int> Original,
11436 const APInt &Zeroable,
11437 const X86Subtarget &Subtarget,
11438 SelectionDAG &DAG) {
11439 uint64_t BlendMask = 0;
11440 bool ForceV1Zero = false, ForceV2Zero = false;
11441 SmallVector<int, 64> Mask(Original);
11442 if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11443 BlendMask))
11444 return SDValue();
11445
11446 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11447 if (ForceV1Zero)
11448 V1 = getZeroVector(VT, Subtarget, DAG, DL);
11449 if (ForceV2Zero)
11450 V2 = getZeroVector(VT, Subtarget, DAG, DL);
11451
11452 unsigned NumElts = VT.getVectorNumElements();
11453
11454 switch (VT.SimpleTy) {
11455 case MVT::v4i64:
11456 case MVT::v8i32:
11457 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11458 [[fallthrough]];
11459 case MVT::v4f64:
11460 case MVT::v8f32:
11461 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11462 [[fallthrough]];
11463 case MVT::v2f64:
11464 case MVT::v2i64:
11465 case MVT::v4f32:
11466 case MVT::v4i32:
11467 case MVT::v8i16:
11468 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
11469 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
11470 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11471 case MVT::v16i16: {
11472 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
11473 SmallVector<int, 8> RepeatedMask;
11474 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11475 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
11476 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
11477 BlendMask = 0;
11478 for (int i = 0; i < 8; ++i)
11479 if (RepeatedMask[i] >= 8)
11480 BlendMask |= 1ull << i;
11481 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11482 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11483 }
11484 // Use PBLENDW for lower/upper lanes and then blend lanes.
11485 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
11486 // merge to VSELECT where useful.
11487 uint64_t LoMask = BlendMask & 0xFF;
11488 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
11489 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
11490 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11491 DAG.getTargetConstant(LoMask, DL, MVT::i8));
11492 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11493 DAG.getTargetConstant(HiMask, DL, MVT::i8));
11494 return DAG.getVectorShuffle(
11495 MVT::v16i16, DL, Lo, Hi,
11496 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
11497 }
11498 [[fallthrough]];
11499 }
11500 case MVT::v32i8:
11501 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
11502 [[fallthrough]];
11503 case MVT::v16i8: {
11504 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
11505
11506 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
11507 if (SDValue Masked =
11508 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11509 return Masked;
11510
11511 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
11512 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11513 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11514 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11515 }
11516
11517 // If we have VPTERNLOG, we can use that as a bit blend.
11518 if (Subtarget.hasVLX())
11519 if (SDValue BitBlend =
11520 lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
11521 return BitBlend;
11522
11523 // Scale the blend by the number of bytes per element.
11524 int Scale = VT.getScalarSizeInBits() / 8;
11525
11526 // This form of blend is always done on bytes. Compute the byte vector
11527 // type.
11528 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11529
11530 // x86 allows load folding with blendvb from the 2nd source operand. But
11531 // we are still using LLVM select here (see comment below), so that's V1.
11532 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
11533 // allow that load-folding possibility.
11534 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
11536 std::swap(V1, V2);
11537 }
11538
11539 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
11540 // mix of LLVM's code generator and the x86 backend. We tell the code
11541 // generator that boolean values in the elements of an x86 vector register
11542 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
11543 // mapping a select to operand #1, and 'false' mapping to operand #2. The
11544 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
11545 // of the element (the remaining are ignored) and 0 in that high bit would
11546 // mean operand #1 while 1 in the high bit would mean operand #2. So while
11547 // the LLVM model for boolean values in vector elements gets the relevant
11548 // bit set, it is set backwards and over constrained relative to x86's
11549 // actual model.
11550 SmallVector<SDValue, 32> VSELECTMask;
11551 for (int i = 0, Size = Mask.size(); i < Size; ++i)
11552 for (int j = 0; j < Scale; ++j)
11553 VSELECTMask.push_back(
11554 Mask[i] < 0
11555 ? DAG.getUNDEF(MVT::i8)
11556 : DAG.getSignedConstant(Mask[i] < Size ? -1 : 0, DL, MVT::i8));
11557
11558 V1 = DAG.getBitcast(BlendVT, V1);
11559 V2 = DAG.getBitcast(BlendVT, V2);
11560 return DAG.getBitcast(
11561 VT,
11562 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
11563 V1, V2));
11564 }
11565 case MVT::v16f32:
11566 case MVT::v8f64:
11567 case MVT::v8i64:
11568 case MVT::v16i32:
11569 case MVT::v32i16:
11570 case MVT::v64i8: {
11571 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
11572 bool OptForSize = DAG.shouldOptForSize();
11573 if (!OptForSize) {
11574 if (SDValue Masked =
11575 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11576 return Masked;
11577 }
11578
11579 // Otherwise load an immediate into a GPR, cast to k-register, and use a
11580 // masked move.
11581 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11582 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11583 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11584 }
11585 default:
11586 llvm_unreachable("Not a supported integer vector type!");
11587 }
11588}
11589
11590/// Try to lower as a blend of elements from two inputs followed by
11591/// a single-input permutation.
11592///
11593/// This matches the pattern where we can blend elements from two inputs and
11594/// then reduce the shuffle to a single-input permutation.
11596 SDValue V1, SDValue V2,
11597 ArrayRef<int> Mask,
11598 SelectionDAG &DAG,
11599 bool ImmBlends = false) {
11600 // We build up the blend mask while checking whether a blend is a viable way
11601 // to reduce the shuffle.
11602 SmallVector<int, 32> BlendMask(Mask.size(), -1);
11603 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
11604
11605 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11606 if (Mask[i] < 0)
11607 continue;
11608
11609 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
11610
11611 if (BlendMask[Mask[i] % Size] < 0)
11612 BlendMask[Mask[i] % Size] = Mask[i];
11613 else if (BlendMask[Mask[i] % Size] != Mask[i])
11614 return SDValue(); // Can't blend in the needed input!
11615
11616 PermuteMask[i] = Mask[i] % Size;
11617 }
11618
11619 // If only immediate blends, then bail if the blend mask can't be widened to
11620 // i16.
11621 unsigned EltSize = VT.getScalarSizeInBits();
11622 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11623 return SDValue();
11624
11625 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11626 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11627}
11628
11629/// Try to lower as an unpack of elements from two inputs followed by
11630/// a single-input permutation.
11631///
11632/// This matches the pattern where we can unpack elements from two inputs and
11633/// then reduce the shuffle to a single-input (wider) permutation.
11635 SDValue V1, SDValue V2,
11636 ArrayRef<int> Mask,
11637 SelectionDAG &DAG) {
11638 int NumElts = Mask.size();
11639 int NumLanes = VT.getSizeInBits() / 128;
11640 int NumLaneElts = NumElts / NumLanes;
11641 int NumHalfLaneElts = NumLaneElts / 2;
11642
11643 bool MatchLo = true, MatchHi = true;
11644 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11645
11646 // Determine UNPCKL/UNPCKH type and operand order.
11647 for (int Elt = 0; Elt != NumElts; ++Elt) {
11648 int M = Mask[Elt];
11649 if (M < 0)
11650 continue;
11651
11652 // Normalize the mask value depending on whether it's V1 or V2.
11653 int NormM = M;
11654 SDValue &Op = Ops[Elt & 1];
11655 if (M < NumElts && (Op.isUndef() || Op == V1))
11656 Op = V1;
11657 else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
11658 Op = V2;
11659 NormM -= NumElts;
11660 } else
11661 return SDValue();
11662
11663 bool MatchLoAnyLane = false, MatchHiAnyLane = false;
11664 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11665 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11666 MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
11667 MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
11668 if (MatchLoAnyLane || MatchHiAnyLane) {
11669 assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
11670 "Failed to match UNPCKLO/UNPCKHI");
11671 break;
11672 }
11673 }
11674 MatchLo &= MatchLoAnyLane;
11675 MatchHi &= MatchHiAnyLane;
11676 if (!MatchLo && !MatchHi)
11677 return SDValue();
11678 }
11679 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11680
11681 // Element indices have changed after unpacking. Calculate permute mask
11682 // so that they will be put back to the position as dictated by the
11683 // original shuffle mask indices.
11684 SmallVector<int, 32> PermuteMask(NumElts, -1);
11685 for (int Elt = 0; Elt != NumElts; ++Elt) {
11686 int M = Mask[Elt];
11687 if (M < 0)
11688 continue;
11689 int NormM = M;
11690 if (NumElts <= M)
11691 NormM -= NumElts;
11692 bool IsFirstOp = M < NumElts;
11693 int BaseMaskElt =
11694 NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
11695 if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
11696 PermuteMask[Elt] = BaseMaskElt;
11697 else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
11698 PermuteMask[Elt] = BaseMaskElt + 1;
11699 assert(PermuteMask[Elt] != -1 &&
11700 "Input mask element is defined but failed to assign permute mask");
11701 }
11702
11703 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11704 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11705 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11706}
11707
11708/// Try to lower a shuffle as a permute of the inputs followed by an
11709/// UNPCK instruction.
11710///
11711/// This specifically targets cases where we end up with alternating between
11712/// the two inputs, and so can permute them into something that feeds a single
11713/// UNPCK instruction. Note that this routine only targets integer vectors
11714/// because for floating point vectors we have a generalized SHUFPS lowering
11715/// strategy that handles everything that doesn't *exactly* match an unpack,
11716/// making this clever lowering unnecessary.
11718 SDValue V1, SDValue V2,
11719 ArrayRef<int> Mask,
11720 const X86Subtarget &Subtarget,
11721 SelectionDAG &DAG) {
11722 int Size = Mask.size();
11723 assert(Mask.size() >= 2 && "Single element masks are invalid.");
11724
11725 // This routine only supports 128-bit integer dual input vectors.
11726 if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
11727 return SDValue();
11728
11729 int NumLoInputs =
11730 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
11731 int NumHiInputs =
11732 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
11733
11734 bool UnpackLo = NumLoInputs >= NumHiInputs;
11735
11736 auto TryUnpack = [&](int ScalarSize, int Scale) {
11737 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
11738 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
11739
11740 for (int i = 0; i < Size; ++i) {
11741 if (Mask[i] < 0)
11742 continue;
11743
11744 // Each element of the unpack contains Scale elements from this mask.
11745 int UnpackIdx = i / Scale;
11746
11747 // We only handle the case where V1 feeds the first slots of the unpack.
11748 // We rely on canonicalization to ensure this is the case.
11749 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
11750 return SDValue();
11751
11752 // Setup the mask for this input. The indexing is tricky as we have to
11753 // handle the unpack stride.
11754 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
11755 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
11756 Mask[i] % Size;
11757 }
11758
11759 // If we will have to shuffle both inputs to use the unpack, check whether
11760 // we can just unpack first and shuffle the result. If so, skip this unpack.
11761 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
11762 !isNoopShuffleMask(V2Mask))
11763 return SDValue();
11764
11765 // Shuffle the inputs into place.
11766 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11767 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11768
11769 // Cast the inputs to the type we will use to unpack them.
11770 MVT UnpackVT =
11771 MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
11772 V1 = DAG.getBitcast(UnpackVT, V1);
11773 V2 = DAG.getBitcast(UnpackVT, V2);
11774
11775 // Unpack the inputs and cast the result back to the desired type.
11776 return DAG.getBitcast(
11777 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
11778 UnpackVT, V1, V2));
11779 };
11780
11781 // We try each unpack from the largest to the smallest to try and find one
11782 // that fits this mask.
11783 int OrigScalarSize = VT.getScalarSizeInBits();
11784 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
11785 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
11786 return Unpack;
11787
11788 // If we're shuffling with a zero vector then we're better off not doing
11789 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
11790 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
11792 return SDValue();
11793
11794 // If none of the unpack-rooted lowerings worked (or were profitable) try an
11795 // initial unpack.
11796 if (NumLoInputs == 0 || NumHiInputs == 0) {
11797 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
11798 "We have to have *some* inputs!");
11799 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
11800
11801 // FIXME: We could consider the total complexity of the permute of each
11802 // possible unpacking. Or at the least we should consider how many
11803 // half-crossings are created.
11804 // FIXME: We could consider commuting the unpacks.
11805
11806 SmallVector<int, 32> PermMask((unsigned)Size, -1);
11807 for (int i = 0; i < Size; ++i) {
11808 if (Mask[i] < 0)
11809 continue;
11810
11811 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
11812
11813 PermMask[i] =
11814 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
11815 }
11816 return DAG.getVectorShuffle(
11817 VT, DL,
11818 DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
11819 V1, V2),
11820 DAG.getUNDEF(VT), PermMask);
11821 }
11822
11823 return SDValue();
11824}
11825
11826/// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11827/// permuting the elements of the result in place.
11829 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11830 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11831 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11832 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11833 (VT.is512BitVector() && !Subtarget.hasBWI()))
11834 return SDValue();
11835
11836 // We don't currently support lane crossing permutes.
11837 if (is128BitLaneCrossingShuffleMask(VT, Mask))
11838 return SDValue();
11839
11840 int Scale = VT.getScalarSizeInBits() / 8;
11841 int NumLanes = VT.getSizeInBits() / 128;
11842 int NumElts = VT.getVectorNumElements();
11843 int NumEltsPerLane = NumElts / NumLanes;
11844
11845 // Determine range of mask elts.
11846 bool Blend1 = true;
11847 bool Blend2 = true;
11848 std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11849 std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11850 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11851 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11852 int M = Mask[Lane + Elt];
11853 if (M < 0)
11854 continue;
11855 if (M < NumElts) {
11856 Blend1 &= (M == (Lane + Elt));
11857 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11858 M = M % NumEltsPerLane;
11859 Range1.first = std::min(Range1.first, M);
11860 Range1.second = std::max(Range1.second, M);
11861 } else {
11862 M -= NumElts;
11863 Blend2 &= (M == (Lane + Elt));
11864 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11865 M = M % NumEltsPerLane;
11866 Range2.first = std::min(Range2.first, M);
11867 Range2.second = std::max(Range2.second, M);
11868 }
11869 }
11870 }
11871
11872 // Bail if we don't need both elements.
11873 // TODO - it might be worth doing this for unary shuffles if the permute
11874 // can be widened.
11875 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11876 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11877 return SDValue();
11878
11879 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11880 return SDValue();
11881
11882 // Rotate the 2 ops so we can access both ranges, then permute the result.
11883 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11884 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11885 SDValue Rotate = DAG.getBitcast(
11886 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11887 DAG.getBitcast(ByteVT, Lo),
11888 DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11889 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11890 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11891 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11892 int M = Mask[Lane + Elt];
11893 if (M < 0)
11894 continue;
11895 if (M < NumElts)
11896 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11897 else
11898 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
11899 }
11900 }
11901 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
11902 };
11903
11904 // Check if the ranges are small enough to rotate from either direction.
11905 if (Range2.second < Range1.first)
11906 return RotateAndPermute(V1, V2, Range1.first, 0);
11907 if (Range1.second < Range2.first)
11908 return RotateAndPermute(V2, V1, Range2.first, NumElts);
11909 return SDValue();
11910}
11911
11913 return isUndefOrEqual(Mask, 0);
11914}
11915
11917 return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
11918}
11919
11920/// Check if the Mask consists of the same element repeated multiple times.
11922 size_t NumUndefs = 0;
11923 std::optional<int> UniqueElt;
11924 for (int Elt : Mask) {
11925 if (Elt == SM_SentinelUndef) {
11926 NumUndefs++;
11927 continue;
11928 }
11929 if (UniqueElt.has_value() && UniqueElt.value() != Elt)
11930 return false;
11931 UniqueElt = Elt;
11932 }
11933 // Make sure the element is repeated enough times by checking the number of
11934 // undefs is small.
11935 return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
11936}
11937
11938/// Generic routine to decompose a shuffle and blend into independent
11939/// blends and permutes.
11940///
11941/// This matches the extremely common pattern for handling combined
11942/// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11943/// operations. It will try to pick the best arrangement of shuffles and
11944/// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
11946 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11947 const APInt &Zeroable, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11948 int NumElts = Mask.size();
11949 int NumLanes = VT.getSizeInBits() / 128;
11950 int NumEltsPerLane = NumElts / NumLanes;
11951 int EltSizeInBits = VT.getScalarSizeInBits();
11952
11953 // Shuffle the input elements into the desired positions in V1 and V2 and
11954 // unpack/blend them together.
11955 bool IsAlternating = true;
11956 bool V1Zero = true, V2Zero = true;
11957 SmallVector<int, 32> V1Mask(NumElts, -1);
11958 SmallVector<int, 32> V2Mask(NumElts, -1);
11959 SmallVector<int, 32> FinalMask(NumElts, -1);
11960 for (int i = 0; i < NumElts; ++i) {
11961 int M = Mask[i];
11962 if (M >= 0 && M < NumElts) {
11963 V1Mask[i] = M;
11964 FinalMask[i] = i;
11965 V1Zero &= Zeroable[i];
11966 IsAlternating &= (i & 1) == 0;
11967 } else if (M >= NumElts) {
11968 V2Mask[i] = M - NumElts;
11969 FinalMask[i] = i + NumElts;
11970 V2Zero &= Zeroable[i];
11971 IsAlternating &= (i & 1) == 1;
11972 }
11973 }
11974
11975 // If we effectively only demand the 0'th element of \p Input, and not only
11976 // as 0'th element, then broadcast said input,
11977 // and change \p InputMask to be a no-op (identity) mask.
11978 auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
11979 &DAG](SDValue &Input,
11980 MutableArrayRef<int> InputMask) {
11981 unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
11982 if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
11983 !X86::mayFoldLoad(Input, Subtarget)))
11984 return;
11985 if (isNoopShuffleMask(InputMask))
11986 return;
11987 assert(isBroadcastShuffleMask(InputMask) &&
11988 "Expected to demand only the 0'th element.");
11989 Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
11990 for (auto I : enumerate(InputMask)) {
11991 int &InputMaskElt = I.value();
11992 if (InputMaskElt >= 0)
11993 InputMaskElt = I.index();
11994 }
11995 };
11996
11997 // Currently, we may need to produce one shuffle per input, and blend results.
11998 // It is possible that the shuffle for one of the inputs is already a no-op.
11999 // See if we can simplify non-no-op shuffles into broadcasts,
12000 // which we consider to be strictly better than an arbitrary shuffle.
12001 if (isNoopOrBroadcastShuffleMask(V1Mask) &&
12003 canonicalizeBroadcastableInput(V1, V1Mask);
12004 canonicalizeBroadcastableInput(V2, V2Mask);
12005 }
12006
12007 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12008 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12009 // the shuffle may be able to fold with a load or other benefit. However, when
12010 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12011 // pre-shuffle first is a better strategy.
12012 bool V1Noop = isNoopShuffleMask(V1Mask);
12013 bool V2Noop = isNoopShuffleMask(V2Mask);
12014 if (!V1Noop && !V2Noop) {
12015 // If we don't have blends, see if we can create a cheap unpack.
12016 if (!Subtarget.hasSSE41() && VT.is128BitVector() &&
12017 (is128BitUnpackShuffleMask(V1Mask, DAG) ||
12018 is128BitUnpackShuffleMask(V2Mask, DAG)))
12019 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12020 DL, VT, V1, V2, Mask, Subtarget, DAG))
12021 return PermUnpack;
12022
12023 // Only prefer immediate blends to unpack/rotate.
12024 if (SDValue BlendPerm =
12025 lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG, true))
12026 return BlendPerm;
12027
12028 // If either input vector provides only a single element which is repeated
12029 // multiple times, unpacking from both input vectors would generate worse
12030 // code. e.g. for
12031 // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
12032 // it is better to process t4 first to create a vector of t4[0], then unpack
12033 // that vector with t2.
12034 if (!V1Zero && !V2Zero && !isSingleElementRepeatedMask(V1Mask) &&
12036 if (SDValue UnpackPerm =
12037 lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
12038 return UnpackPerm;
12039
12041 DL, VT, V1, V2, Mask, Subtarget, DAG))
12042 return RotatePerm;
12043
12044 // Unpack/rotate failed - try again with variable blends.
12045 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12046 DAG))
12047 return BlendPerm;
12048
12049 if (EltSizeInBits >= 32)
12050 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12051 DL, VT, V1, V2, Mask, Subtarget, DAG))
12052 return PermUnpack;
12053 }
12054
12055 // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12056 // UNPCKL(SHUFFLE, SHUFFLE) pattern unless BLENDI is cheap.
12057 // TODO: It doesn't have to be alternating - but each lane mustn't have more
12058 // than half the elements coming from each source.
12059 bool PreferBlend = EltSizeInBits == 16 && (V1Noop || V2Noop) &&
12060 Subtarget.hasSSE41() &&
12061 is128BitLaneRepeatedShuffleMask(VT, FinalMask);
12062 if (!PreferBlend && IsAlternating && EltSizeInBits < 32) {
12063 V1Mask.assign(NumElts, -1);
12064 V2Mask.assign(NumElts, -1);
12065 FinalMask.assign(NumElts, -1);
12066 for (int i = 0; i != NumElts; i += NumEltsPerLane)
12067 for (int j = 0; j != NumEltsPerLane; ++j) {
12068 int M = Mask[i + j];
12069 if (M >= 0 && M < NumElts) {
12070 V1Mask[i + (j / 2)] = M;
12071 FinalMask[i + j] = i + (j / 2);
12072 } else if (M >= NumElts) {
12073 V2Mask[i + (j / 2)] = M - NumElts;
12074 FinalMask[i + j] = i + (j / 2) + NumElts;
12075 }
12076 }
12077 }
12078
12079 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12080 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12081 return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12082}
12083
12084static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12085 const X86Subtarget &Subtarget,
12086 ArrayRef<int> Mask) {
12087 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12088 assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12089
12090 // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12091 int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12092 int MaxSubElts = 64 / EltSizeInBits;
12093 unsigned RotateAmt, NumSubElts;
12094 if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, MinSubElts,
12095 MaxSubElts, NumSubElts, RotateAmt))
12096 return -1;
12097 unsigned NumElts = Mask.size();
12098 MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12099 RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12100 return RotateAmt;
12101}
12102
12103/// Lower shuffle using X86ISD::VROTLI rotations.
12105 ArrayRef<int> Mask,
12106 const X86Subtarget &Subtarget,
12107 SelectionDAG &DAG) {
12108 // Only XOP + AVX512 targets have bit rotation instructions.
12109 // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12110 bool IsLegal =
12111 (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12112 if (!IsLegal && Subtarget.hasSSE3())
12113 return SDValue();
12114
12115 MVT RotateVT;
12116 int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12117 Subtarget, Mask);
12118 if (RotateAmt < 0)
12119 return SDValue();
12120
12121 // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12122 // expanded to OR(SRL,SHL), will be more efficient, but if they can
12123 // widen to vXi16 or more then existing lowering should will be better.
12124 if (!IsLegal) {
12125 if ((RotateAmt % 16) == 0)
12126 return SDValue();
12127 unsigned ShlAmt = RotateAmt;
12128 unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12129 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, RotateVT, V1,
12130 ShlAmt, DAG);
12131 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, RotateVT, V1,
12132 SrlAmt, DAG);
12133 SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12134 return DAG.getBitcast(VT, Rot);
12135 }
12136
12137 SDValue Rot =
12138 DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12139 DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12140 return DAG.getBitcast(VT, Rot);
12141}
12142
12143/// Try to match a vector shuffle as an element rotation.
12144///
12145/// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
12147 ArrayRef<int> Mask) {
12148 int NumElts = Mask.size();
12149
12150 // We need to detect various ways of spelling a rotation:
12151 // [11, 12, 13, 14, 15, 0, 1, 2]
12152 // [-1, 12, 13, 14, -1, -1, 1, -1]
12153 // [-1, -1, -1, -1, -1, -1, 1, 2]
12154 // [ 3, 4, 5, 6, 7, 8, 9, 10]
12155 // [-1, 4, 5, 6, -1, -1, 9, -1]
12156 // [-1, 4, 5, 6, -1, -1, -1, -1]
12157 int Rotation = 0;
12158 SDValue Lo, Hi;
12159 for (int i = 0; i < NumElts; ++i) {
12160 int M = Mask[i];
12161 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
12162 "Unexpected mask index.");
12163 if (M < 0)
12164 continue;
12165
12166 // Determine where a rotated vector would have started.
12167 int StartIdx = i - (M % NumElts);
12168 if (StartIdx == 0)
12169 // The identity rotation isn't interesting, stop.
12170 return -1;
12171
12172 // If we found the tail of a vector the rotation must be the missing
12173 // front. If we found the head of a vector, it must be how much of the
12174 // head.
12175 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12176
12177 if (Rotation == 0)
12178 Rotation = CandidateRotation;
12179 else if (Rotation != CandidateRotation)
12180 // The rotations don't match, so we can't match this mask.
12181 return -1;
12182
12183 // Compute which value this mask is pointing at.
12184 SDValue MaskV = M < NumElts ? V1 : V2;
12185
12186 // Compute which of the two target values this index should be assigned
12187 // to. This reflects whether the high elements are remaining or the low
12188 // elements are remaining.
12189 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12190
12191 // Either set up this value if we've not encountered it before, or check
12192 // that it remains consistent.
12193 if (!TargetV)
12194 TargetV = MaskV;
12195 else if (TargetV != MaskV)
12196 // This may be a rotation, but it pulls from the inputs in some
12197 // unsupported interleaving.
12198 return -1;
12199 }
12200
12201 // Check that we successfully analyzed the mask, and normalize the results.
12202 assert(Rotation != 0 && "Failed to locate a viable rotation!");
12203 assert((Lo || Hi) && "Failed to find a rotated input vector!");
12204 if (!Lo)
12205 Lo = Hi;
12206 else if (!Hi)
12207 Hi = Lo;
12208
12209 V1 = Lo;
12210 V2 = Hi;
12211
12212 return Rotation;
12213}
12214
12215/// Try to lower a vector shuffle as a byte rotation.
12216///
12217/// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12218/// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12219/// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12220/// try to generically lower a vector shuffle through such an pattern. It
12221/// does not check for the profitability of lowering either as PALIGNR or
12222/// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12223/// This matches shuffle vectors that look like:
12224///
12225/// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12226///
12227/// Essentially it concatenates V1 and V2, shifts right by some number of
12228/// elements, and takes the low elements as the result. Note that while this is
12229/// specified as a *right shift* because x86 is little-endian, it is a *left
12230/// rotate* of the vector lanes.
12232 ArrayRef<int> Mask) {
12233 // Don't accept any shuffles with zero elements.
12234 if (isAnyZero(Mask))
12235 return -1;
12236
12237 // PALIGNR works on 128-bit lanes.
12238 SmallVector<int, 16> RepeatedMask;
12239 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12240 return -1;
12241
12242 int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12243 if (Rotation <= 0)
12244 return -1;
12245
12246 // PALIGNR rotates bytes, so we need to scale the
12247 // rotation based on how many bytes are in the vector lane.
12248 int NumElts = RepeatedMask.size();
12249 int Scale = 16 / NumElts;
12250 return Rotation * Scale;
12251}
12252
12254 SDValue V2, ArrayRef<int> Mask,
12255 const X86Subtarget &Subtarget,
12256 SelectionDAG &DAG) {
12257 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12258
12259 SDValue Lo = V1, Hi = V2;
12260 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12261 if (ByteRotation <= 0)
12262 return SDValue();
12263
12264 // Cast the inputs to i8 vector of correct length to match PALIGNR or
12265 // PSLLDQ/PSRLDQ.
12266 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12267 Lo = DAG.getBitcast(ByteVT, Lo);
12268 Hi = DAG.getBitcast(ByteVT, Hi);
12269
12270 // SSSE3 targets can use the palignr instruction.
12271 if (Subtarget.hasSSSE3()) {
12272 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
12273 "512-bit PALIGNR requires BWI instructions");
12274 return DAG.getBitcast(
12275 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12276 DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12277 }
12278
12279 assert(VT.is128BitVector() &&
12280 "Rotate-based lowering only supports 128-bit lowering!");
12281 assert(Mask.size() <= 16 &&
12282 "Can shuffle at most 16 bytes in a 128-bit vector!");
12283 assert(ByteVT == MVT::v16i8 &&
12284 "SSE2 rotate lowering only needed for v16i8!");
12285
12286 // Default SSE2 implementation
12287 int LoByteShift = 16 - ByteRotation;
12288 int HiByteShift = ByteRotation;
12289
12290 SDValue LoShift =
12291 DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12292 DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12293 SDValue HiShift =
12294 DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12295 DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12296 return DAG.getBitcast(VT,
12297 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12298}
12299
12300/// Try to lower a vector shuffle as a dword/qword rotation.
12301///
12302/// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12303/// rotation of the concatenation of two vectors; This routine will
12304/// try to generically lower a vector shuffle through such an pattern.
12305///
12306/// Essentially it concatenates V1 and V2, shifts right by some number of
12307/// elements, and takes the low elements as the result. Note that while this is
12308/// specified as a *right shift* because x86 is little-endian, it is a *left
12309/// rotate* of the vector lanes.
12311 SDValue V2, ArrayRef<int> Mask,
12312 const APInt &Zeroable,
12313 const X86Subtarget &Subtarget,
12314 SelectionDAG &DAG) {
12315 unsigned EltBits = VT.getScalarSizeInBits();
12316 if (EltBits != 32 && EltBits != 64)
12317 return SDValue();
12318
12320
12321 // 128/256-bit vectors are only supported with VLX.
12322 assert((Subtarget.hasVLX() ||
12323 (!AlignVT.is128BitVector() && !AlignVT.is256BitVector())) &&
12324 "VLX required for 128/256-bit vectors");
12325
12326 auto emitVALIGN = [&](SDValue Lo, SDValue Hi, unsigned Imm) -> SDValue {
12327 SDValue AlignLo = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Lo) : Lo;
12328 SDValue AlignHi = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Hi) : Hi;
12329 SDValue Res = DAG.getNode(X86ISD::VALIGN, DL, AlignVT, AlignLo, AlignHi,
12330 DAG.getTargetConstant(Imm, DL, MVT::i8));
12331 return VT.isFloatingPoint() ? DAG.getBitcast(VT, Res) : Res;
12332 };
12333
12334 SDValue Lo = V1, Hi = V2;
12335 int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12336 if (0 < Rotation)
12337 return emitVALIGN(Lo, Hi, Rotation);
12338
12339 // See if we can use VALIGN as a cross-lane version of VSHLDQ/VSRLDQ.
12340 // TODO: Pull this out as a matchShuffleAsElementShift helper?
12341 // TODO: We can probably make this more aggressive and use shift-pairs like
12342 // lowerShuffleAsByteShiftMask.
12343 unsigned NumElts = Mask.size();
12344 unsigned ZeroLo = Zeroable.countr_one();
12345 unsigned ZeroHi = Zeroable.countl_one();
12346 assert((ZeroLo + ZeroHi) < NumElts && "Zeroable shuffle detected");
12347 if (!ZeroLo && !ZeroHi)
12348 return SDValue();
12349
12350 if (ZeroLo) {
12351 SDValue Src = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12352 int Low = Mask[ZeroLo] < (int)NumElts ? 0 : NumElts;
12353 if (isSequentialOrUndefInRange(Mask, ZeroLo, NumElts - ZeroLo, Low))
12354 return emitVALIGN(Src, getZeroVector(AlignVT, Subtarget, DAG, DL),
12355 NumElts - ZeroLo);
12356 }
12357
12358 if (ZeroHi) {
12359 SDValue Src = Mask[0] < (int)NumElts ? V1 : V2;
12360 int Low = Mask[0] < (int)NumElts ? 0 : NumElts;
12361 if (isSequentialOrUndefInRange(Mask, 0, NumElts - ZeroHi, Low + ZeroHi))
12362 return emitVALIGN(getZeroVector(AlignVT, Subtarget, DAG, DL), Src,
12363 ZeroHi);
12364 }
12365
12366 return SDValue();
12367}
12368
12369/// Try to lower a vector shuffle as a byte shift sequence.
12371 SDValue V2, ArrayRef<int> Mask,
12372 const APInt &Zeroable,
12373 const X86Subtarget &Subtarget,
12374 SelectionDAG &DAG) {
12375 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12376 assert(VT.is128BitVector() && "Only 128-bit vectors supported");
12377
12378 // We need a shuffle that has zeros at one/both ends and a sequential
12379 // shuffle from one source within.
12380 unsigned ZeroLo = Zeroable.countr_one();
12381 unsigned ZeroHi = Zeroable.countl_one();
12382 if (!ZeroLo && !ZeroHi)
12383 return SDValue();
12384
12385 unsigned NumElts = Mask.size();
12386 unsigned Len = NumElts - (ZeroLo + ZeroHi);
12387 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12388 return SDValue();
12389
12390 unsigned Scale = VT.getScalarSizeInBits() / 8;
12391 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12392 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12393 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12394 return SDValue();
12395
12396 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12397 Res = DAG.getBitcast(MVT::v16i8, Res);
12398
12399 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12400 // inner sequential set of elements, possibly offset:
12401 // 01234567 --> zzzzzz01 --> 1zzzzzzz
12402 // 01234567 --> 4567zzzz --> zzzzz456
12403 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12404 if (ZeroLo == 0) {
12405 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12406 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12407 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12408 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12409 DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12410 } else if (ZeroHi == 0) {
12411 unsigned Shift = Mask[ZeroLo] % NumElts;
12412 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12413 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12414 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12415 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12416 } else if (!Subtarget.hasSSSE3()) {
12417 // If we don't have PSHUFB then its worth avoiding an AND constant mask
12418 // by performing 3 byte shifts. Shuffle combining can kick in above that.
12419 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12420 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12421 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12422 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12423 Shift += Mask[ZeroLo] % NumElts;
12424 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12425 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12426 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12427 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12428 } else
12429 return SDValue();
12430
12431 return DAG.getBitcast(VT, Res);
12432}
12433
12434/// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12435///
12436/// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12437/// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12438/// matches elements from one of the input vectors shuffled to the left or
12439/// right with zeroable elements 'shifted in'. It handles both the strictly
12440/// bit-wise element shifts and the byte shift across an entire 128-bit double
12441/// quad word lane.
12442///
12443/// PSHL : (little-endian) left bit shift.
12444/// [ zz, 0, zz, 2 ]
12445/// [ -1, 4, zz, -1 ]
12446/// PSRL : (little-endian) right bit shift.
12447/// [ 1, zz, 3, zz]
12448/// [ -1, -1, 7, zz]
12449/// PSLLDQ : (little-endian) left byte shift
12450/// [ zz, 0, 1, 2, 3, 4, 5, 6]
12451/// [ zz, zz, -1, -1, 2, 3, 4, -1]
12452/// [ zz, zz, zz, zz, zz, zz, -1, 1]
12453/// PSRLDQ : (little-endian) right byte shift
12454/// [ 5, 6, 7, zz, zz, zz, zz, zz]
12455/// [ -1, 5, 6, 7, zz, zz, zz, zz]
12456/// [ 1, 2, -1, -1, -1, -1, zz, zz]
12457static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12458 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12459 int MaskOffset, const APInt &Zeroable,
12460 const X86Subtarget &Subtarget) {
12461 int Size = Mask.size();
12462 unsigned SizeInBits = Size * ScalarSizeInBits;
12463
12464 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12465 for (int i = 0; i < Size; i += Scale)
12466 for (int j = 0; j < Shift; ++j)
12467 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12468 return false;
12469
12470 return true;
12471 };
12472
12473 auto MatchShift = [&](int Shift, int Scale, bool Left) {
12474 for (int i = 0; i != Size; i += Scale) {
12475 unsigned Pos = Left ? i + Shift : i;
12476 unsigned Low = Left ? i : i + Shift;
12477 unsigned Len = Scale - Shift;
12478 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12479 return -1;
12480 }
12481
12482 int ShiftEltBits = ScalarSizeInBits * Scale;
12483 bool ByteShift = ShiftEltBits > 64;
12484 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12485 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12486 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12487
12488 // Normalize the scale for byte shifts to still produce an i64 element
12489 // type.
12490 Scale = ByteShift ? Scale / 2 : Scale;
12491
12492 // We need to round trip through the appropriate type for the shift.
12493 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12494 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12495 : MVT::getVectorVT(ShiftSVT, Size / Scale);
12496 return ShiftAmt;
12497 };
12498
12499 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12500 // keep doubling the size of the integer elements up to that. We can
12501 // then shift the elements of the integer vector by whole multiples of
12502 // their width within the elements of the larger integer vector. Test each
12503 // multiple to see if we can find a match with the moved element indices
12504 // and that the shifted in elements are all zeroable.
12505 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12506 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12507 for (int Shift = 1; Shift != Scale; ++Shift)
12508 for (bool Left : {true, false})
12509 if (CheckZeros(Shift, Scale, Left)) {
12510 int ShiftAmt = MatchShift(Shift, Scale, Left);
12511 if (0 < ShiftAmt)
12512 return ShiftAmt;
12513 }
12514
12515 // no match
12516 return -1;
12517}
12518
12520 SDValue V2, ArrayRef<int> Mask,
12521 const APInt &Zeroable,
12522 const X86Subtarget &Subtarget,
12523 SelectionDAG &DAG, bool BitwiseOnly) {
12524 int Size = Mask.size();
12525 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12526
12527 MVT ShiftVT;
12528 SDValue V = V1;
12529 unsigned Opcode;
12530
12531 // Try to match shuffle against V1 shift.
12532 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12533 Mask, 0, Zeroable, Subtarget);
12534
12535 // If V1 failed, try to match shuffle against V2 shift.
12536 if (ShiftAmt < 0) {
12537 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12538 Mask, Size, Zeroable, Subtarget);
12539 V = V2;
12540 }
12541
12542 if (ShiftAmt < 0)
12543 return SDValue();
12544
12545 if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
12546 return SDValue();
12547
12548 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
12549 "Illegal integer vector type");
12550 V = DAG.getBitcast(ShiftVT, V);
12551 V = DAG.getNode(Opcode, DL, ShiftVT, V,
12552 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12553 return DAG.getBitcast(VT, V);
12554}
12555
12556/// Try to match a vector shuffle as a X86ISD::VSHLD funnel shift.
12557static int matchShuffleAsVSHLD(MVT &ShiftVT, SDValue &V1, SDValue &V2,
12558 unsigned ScalarSizeInBits, ArrayRef<int> Mask) {
12559 assert(isPowerOf2_32(ScalarSizeInBits) && ScalarSizeInBits >= 8 &&
12560 "Unexpected element size");
12561 int Size = Mask.size();
12563 return -1;
12564
12565 SmallVector<int, 32> FunnelMask(Size);
12566 for (int Scale = 2; (Scale * ScalarSizeInBits) <= 64; Scale *= 2) {
12567 for (int Shift = 1; Shift != Scale; ++Shift) {
12568 for (int Elt = 0; Elt != Size; Elt += Scale) {
12569 std::iota(FunnelMask.begin() + Elt, FunnelMask.begin() + Elt + Shift,
12570 Elt + Size + (Scale - Shift));
12571 std::iota(FunnelMask.begin() + Elt + Shift,
12572 FunnelMask.begin() + Elt + Scale, Elt);
12573 }
12574 if (isShuffleEquivalent(Mask, FunnelMask)) {
12575 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12576 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12577 return Shift * ScalarSizeInBits;
12578 }
12580 if (isShuffleEquivalent(Mask, FunnelMask)) {
12581 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12582 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12583 std::swap(V1, V2);
12584 return Shift * ScalarSizeInBits;
12585 }
12586 }
12587 }
12588
12589 return -1;
12590}
12591
12592// EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12593// Remainder of lower half result is zero and upper half is all undef.
12595 ArrayRef<int> Mask, uint64_t &BitLen,
12596 uint64_t &BitIdx, const APInt &Zeroable) {
12597 int Size = Mask.size();
12598 int HalfSize = Size / 2;
12599 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12600 assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
12601
12602 // Upper half must be undefined.
12603 if (!isUndefUpperHalf(Mask))
12604 return false;
12605
12606 // Determine the extraction length from the part of the
12607 // lower half that isn't zeroable.
12608 int Len = HalfSize;
12609 for (; Len > 0; --Len)
12610 if (!Zeroable[Len - 1])
12611 break;
12612 assert(Len > 0 && "Zeroable shuffle mask");
12613
12614 // Attempt to match first Len sequential elements from the lower half.
12615 SDValue Src;
12616 int Idx = -1;
12617 for (int i = 0; i != Len; ++i) {
12618 int M = Mask[i];
12619 if (M == SM_SentinelUndef)
12620 continue;
12621 SDValue &V = (M < Size ? V1 : V2);
12622 M = M % Size;
12623
12624 // The extracted elements must start at a valid index and all mask
12625 // elements must be in the lower half.
12626 if (i > M || M >= HalfSize)
12627 return false;
12628
12629 if (Idx < 0 || (Src == V && Idx == (M - i))) {
12630 Src = V;
12631 Idx = M - i;
12632 continue;
12633 }
12634 return false;
12635 }
12636
12637 if (!Src || Idx < 0)
12638 return false;
12639
12640 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12641 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12642 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12643 V1 = Src;
12644 return true;
12645}
12646
12647// INSERTQ: Extract lowest Len elements from lower half of second source and
12648// insert over first source, starting at Idx.
12649// { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
12651 ArrayRef<int> Mask, uint64_t &BitLen,
12652 uint64_t &BitIdx) {
12653 int Size = Mask.size();
12654 int HalfSize = Size / 2;
12655 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12656
12657 // Upper half must be undefined.
12658 if (!isUndefUpperHalf(Mask))
12659 return false;
12660
12661 for (int Idx = 0; Idx != HalfSize; ++Idx) {
12662 SDValue Base;
12663
12664 // Attempt to match first source from mask before insertion point.
12665 if (isUndefInRange(Mask, 0, Idx)) {
12666 /* EMPTY */
12667 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12668 Base = V1;
12669 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12670 Base = V2;
12671 } else {
12672 continue;
12673 }
12674
12675 // Extend the extraction length looking to match both the insertion of
12676 // the second source and the remaining elements of the first.
12677 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12678 SDValue Insert;
12679 int Len = Hi - Idx;
12680
12681 // Match insertion.
12682 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12683 Insert = V1;
12684 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12685 Insert = V2;
12686 } else {
12687 continue;
12688 }
12689
12690 // Match the remaining elements of the lower half.
12691 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12692 /* EMPTY */
12693 } else if ((!Base || (Base == V1)) &&
12694 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12695 Base = V1;
12696 } else if ((!Base || (Base == V2)) &&
12697 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12698 Size + Hi)) {
12699 Base = V2;
12700 } else {
12701 continue;
12702 }
12703
12704 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12705 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12706 V1 = Base;
12707 V2 = Insert;
12708 return true;
12709 }
12710 }
12711
12712 return false;
12713}
12714
12715/// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
12717 SDValue V2, ArrayRef<int> Mask,
12718 const APInt &Zeroable, SelectionDAG &DAG) {
12719 uint64_t BitLen, BitIdx;
12720 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12721 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12722 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12723 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12724
12725 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12726 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12727 V2 ? V2 : DAG.getUNDEF(VT),
12728 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12729 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12730
12731 return SDValue();
12732}
12733
12734/// Lower a vector shuffle as an any/signed/zero extension.
12735///
12736/// Given a specific number of elements, element bit width, and extension
12737/// stride, produce either an extension based on the available
12738/// features of the subtarget. The extended elements are consecutive and
12739/// begin and can start from an offsetted element index in the input; to
12740/// avoid excess shuffling the offset must either being in the bottom lane
12741/// or at the start of a higher lane. All extended elements must be from
12742/// the same lane.
12744 int Scale, int Offset,
12745 unsigned ExtOpc, SDValue InputV,
12746 ArrayRef<int> Mask,
12747 const X86Subtarget &Subtarget,
12748 SelectionDAG &DAG) {
12749 assert(Scale > 1 && "Need a scale to extend.");
12750 assert(ISD::isExtOpcode(ExtOpc) && "Unsupported extension");
12751 int EltBits = VT.getScalarSizeInBits();
12752 int NumElements = VT.getVectorNumElements();
12753 int NumEltsPerLane = 128 / EltBits;
12754 int OffsetLane = Offset / NumEltsPerLane;
12755 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12756 "Only 8, 16, and 32 bit elements can be extended.");
12757 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12758 assert(0 <= Offset && "Extension offset must be positive.");
12759 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12760 "Extension offset must be in the first lane or start an upper lane.");
12761
12762 // Check that an index is in same lane as the base offset.
12763 auto SafeOffset = [&](int Idx) {
12764 return OffsetLane == (Idx / NumEltsPerLane);
12765 };
12766
12767 // Shift along an input so that the offset base moves to the first element.
12768 auto ShuffleOffset = [&](SDValue V) {
12769 if (!Offset)
12770 return V;
12771
12772 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12773 for (int i = 0; i * Scale < NumElements; ++i) {
12774 int SrcIdx = i + Offset;
12775 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12776 }
12777 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12778 };
12779
12780 // Found a valid a/zext mask! Try various lowering strategies based on the
12781 // input type and available ISA extensions.
12782 if (Subtarget.hasSSE41()) {
12783 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12784 // PUNPCK will catch this in a later shuffle match.
12785 if (Offset && Scale == 2 && VT.is128BitVector())
12786 return SDValue();
12787 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12788 NumElements / Scale);
12789 InputV = DAG.getBitcast(VT, InputV);
12790 InputV = ShuffleOffset(InputV);
12791 InputV = getEXTEND_VECTOR_INREG(ExtOpc, DL, ExtVT, InputV, DAG);
12792 return DAG.getBitcast(VT, InputV);
12793 }
12794
12795 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12796 InputV = DAG.getBitcast(VT, InputV);
12797 bool AnyExt = ExtOpc == ISD::ANY_EXTEND;
12798
12799 // TODO: Add pre-SSE41 SIGN_EXTEND_VECTOR_INREG handling.
12800 if (ExtOpc == ISD::SIGN_EXTEND)
12801 return SDValue();
12802
12803 // For any extends we can cheat for larger element sizes and use shuffle
12804 // instructions that can fold with a load and/or copy.
12805 if (AnyExt && EltBits == 32) {
12806 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12807 -1};
12808 return DAG.getBitcast(
12809 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12810 DAG.getBitcast(MVT::v4i32, InputV),
12811 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12812 }
12813 if (AnyExt && EltBits == 16 && Scale > 2) {
12814 int PSHUFDMask[4] = {Offset / 2, -1,
12815 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12816 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12817 DAG.getBitcast(MVT::v4i32, InputV),
12818 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12819 int PSHUFWMask[4] = {1, -1, -1, -1};
12820 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12821 return DAG.getBitcast(
12822 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12823 DAG.getBitcast(MVT::v8i16, InputV),
12824 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12825 }
12826
12827 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12828 // to 64-bits.
12829 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12830 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12831 assert(VT.is128BitVector() && "Unexpected vector width!");
12832
12833 int LoIdx = Offset * EltBits;
12834 SDValue Lo = DAG.getBitcast(
12835 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12836 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12837 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12838
12839 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12840 return DAG.getBitcast(VT, Lo);
12841
12842 int HiIdx = (Offset + 1) * EltBits;
12843 SDValue Hi = DAG.getBitcast(
12844 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12845 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12846 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12847 return DAG.getBitcast(VT,
12848 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12849 }
12850
12851 // If this would require more than 2 unpack instructions to expand, use
12852 // pshufb when available. We can only use more than 2 unpack instructions
12853 // when zero extending i8 elements which also makes it easier to use pshufb.
12854 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12855 assert(NumElements == 16 && "Unexpected byte vector width!");
12856 SDValue PSHUFBMask[16];
12857 for (int i = 0; i < 16; ++i) {
12858 int Idx = Offset + (i / Scale);
12859 if ((i % Scale == 0 && SafeOffset(Idx))) {
12860 PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12861 continue;
12862 }
12863 PSHUFBMask[i] =
12864 AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12865 }
12866 InputV = DAG.getBitcast(MVT::v16i8, InputV);
12867 return DAG.getBitcast(
12868 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12869 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12870 }
12871
12872 // If we are extending from an offset, ensure we start on a boundary that
12873 // we can unpack from.
12874 int AlignToUnpack = Offset % (NumElements / Scale);
12875 if (AlignToUnpack) {
12876 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12877 for (int i = AlignToUnpack; i < NumElements; ++i)
12878 ShMask[i - AlignToUnpack] = i;
12879 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12880 Offset -= AlignToUnpack;
12881 }
12882
12883 // Otherwise emit a sequence of unpacks.
12884 do {
12885 unsigned UnpackLoHi = X86ISD::UNPCKL;
12886 if (Offset >= (NumElements / 2)) {
12887 UnpackLoHi = X86ISD::UNPCKH;
12888 Offset -= (NumElements / 2);
12889 }
12890
12891 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12892 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12893 : getZeroVector(InputVT, Subtarget, DAG, DL);
12894 InputV = DAG.getBitcast(InputVT, InputV);
12895 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12896 Scale /= 2;
12897 EltBits *= 2;
12898 NumElements /= 2;
12899 } while (Scale > 1);
12900 return DAG.getBitcast(VT, InputV);
12901}
12902
12903/// Try to lower a vector shuffle as a zero extension on any microarch.
12904///
12905/// This routine will try to do everything in its power to cleverly lower
12906/// a shuffle which happens to match the pattern of a zero extend. It doesn't
12907/// check for the profitability of this lowering, it tries to aggressively
12908/// match this pattern. It will use all of the micro-architectural details it
12909/// can to emit an efficient lowering. It handles both blends with all-zero
12910/// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12911/// masking out later).
12912///
12913/// The reason we have dedicated lowering for zext-style shuffles is that they
12914/// are both incredibly common and often quite performance sensitive.
12916 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12917 const APInt &Zeroable, const X86Subtarget &Subtarget,
12918 SelectionDAG &DAG) {
12919 int Bits = VT.getSizeInBits();
12920 int NumLanes = Bits / 128;
12921 int NumElements = VT.getVectorNumElements();
12922 int NumEltsPerLane = NumElements / NumLanes;
12923 assert(VT.getScalarSizeInBits() <= 32 &&
12924 "Exceeds 32-bit integer zero extension limit");
12925 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12926
12927 // Define a helper function to check a particular ext-scale and lower to it if
12928 // valid.
12929 auto Lower = [&](int Scale) -> SDValue {
12930 SDValue InputV;
12931 bool AnyExt = true;
12932 int Offset = 0;
12933 int Matches = 0;
12934 for (int i = 0; i < NumElements; ++i) {
12935 int M = Mask[i];
12936 if (M < 0)
12937 continue; // Valid anywhere but doesn't tell us anything.
12938 if (i % Scale != 0) {
12939 // Each of the extended elements need to be zeroable.
12940 if (!Zeroable[i])
12941 return SDValue();
12942
12943 // We no longer are in the anyext case.
12944 AnyExt = false;
12945 continue;
12946 }
12947
12948 // Each of the base elements needs to be consecutive indices into the
12949 // same input vector.
12950 SDValue V = M < NumElements ? V1 : V2;
12951 M = M % NumElements;
12952 if (!InputV) {
12953 InputV = V;
12954 Offset = M - (i / Scale);
12955 } else if (InputV != V)
12956 return SDValue(); // Flip-flopping inputs.
12957
12958 // Offset must start in the lowest 128-bit lane or at the start of an
12959 // upper lane.
12960 // FIXME: Is it ever worth allowing a negative base offset?
12961 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12962 (Offset % NumEltsPerLane) == 0))
12963 return SDValue();
12964
12965 // If we are offsetting, all referenced entries must come from the same
12966 // lane.
12967 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12968 return SDValue();
12969
12970 if ((M % NumElements) != (Offset + (i / Scale)))
12971 return SDValue(); // Non-consecutive strided elements.
12972 Matches++;
12973 }
12974
12975 // If we fail to find an input, we have a zero-shuffle which should always
12976 // have already been handled.
12977 // FIXME: Maybe handle this here in case during blending we end up with one?
12978 if (!InputV)
12979 return SDValue();
12980
12981 // If we are offsetting, don't extend if we only match a single input, we
12982 // can always do better by using a basic PSHUF or PUNPCK.
12983 if (Offset != 0 && Matches < 2)
12984 return SDValue();
12985
12986 unsigned ExtOpc = AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND;
12987 return lowerShuffleAsSpecificExtension(DL, VT, Scale, Offset, ExtOpc,
12988 InputV, Mask, Subtarget, DAG);
12989 };
12990
12991 // Match against a foldable v4i32 VZEXT_MOVL zero-extending instruction.
12992 // TODO: Add v8i16 (with FP16) support when we have test coverage.
12993 if (VT == MVT::v4i32 &&
12994 (V1.getOpcode() == ISD::SCALAR_TO_VECTOR || isa<MemSDNode>(V1)) &&
12995 Mask[0] == 0 && (NumElements - 1) == (int)Zeroable.countLeadingOnes())
12996 return DAG.getNode(X86ISD::VZEXT_MOVL, DL, VT, V1);
12997
12998 // The widest scale possible for extending is to a 64-bit integer.
12999 assert(Bits % 64 == 0 &&
13000 "The number of bits in a vector must be divisible by 64 on x86!");
13001 int NumExtElements = Bits / 64;
13002
13003 // Each iteration, try extending the elements half as much, but into twice as
13004 // many elements.
13005 for (; NumExtElements < NumElements; NumExtElements *= 2) {
13006 assert(NumElements % NumExtElements == 0 &&
13007 "The input vector size must be divisible by the extended size.");
13008 if (SDValue V = Lower(NumElements / NumExtElements))
13009 return V;
13010 }
13011
13012 // General extends failed, but 128-bit vectors may be able to use MOVQ.
13013 if (Bits != 128)
13014 return SDValue();
13015
13016 // Returns one of the source operands if the shuffle can be reduced to a
13017 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13018 auto CanZExtLowHalf = [&]() {
13019 for (int i = NumElements / 2; i != NumElements; ++i)
13020 if (!Zeroable[i])
13021 return SDValue();
13022 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13023 return V1;
13024 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13025 return V2;
13026 return SDValue();
13027 };
13028
13029 if (SDValue V = CanZExtLowHalf()) {
13030 V = DAG.getBitcast(MVT::v2i64, V);
13031 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13032 return DAG.getBitcast(VT, V);
13033 }
13034
13035 // No viable ext lowering found.
13036 return SDValue();
13037}
13038
13039/// Try to get a scalar value for a specific element of a vector.
13040///
13041/// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13043 SelectionDAG &DAG) {
13044 MVT VT = V.getSimpleValueType();
13045 MVT EltVT = VT.getVectorElementType();
13046 V = peekThroughBitcasts(V);
13047
13048 // If the bitcasts shift the element size, we can't extract an equivalent
13049 // element from it.
13050 MVT NewVT = V.getSimpleValueType();
13051 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13052 return SDValue();
13053
13054 if (V.getOpcode() == ISD::BUILD_VECTOR ||
13055 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13056 // Ensure the scalar operand is the same size as the destination.
13057 // FIXME: Add support for scalar truncation where possible.
13058 SDValue S = V.getOperand(Idx);
13059 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13060 return DAG.getBitcast(EltVT, S);
13061 }
13062
13063 return SDValue();
13064}
13065
13066/// Helper to test for a load that can be folded with x86 shuffles.
13067///
13068/// This is particularly important because the set of instructions varies
13069/// significantly based on whether the operand is a load or not.
13071 return V.hasOneUse() &&
13073}
13074
13075template<typename T>
13076static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
13077 T EltVT = VT.getScalarType();
13078 return (EltVT == MVT::bf16 && !Subtarget.hasAVX10_2()) ||
13079 (EltVT == MVT::f16 && !Subtarget.hasFP16());
13080}
13081
13082template<typename T>
13083static bool isBF16orSoftF16(T VT, const X86Subtarget &Subtarget) {
13084 T EltVT = VT.getScalarType();
13085 return EltVT == MVT::bf16 || (EltVT == MVT::f16 && !Subtarget.hasFP16());
13086}
13087
13088/// Try to lower insertion of a single element into a zero vector.
13089///
13090/// This is a common pattern that we have especially efficient patterns to lower
13091/// across all subtarget feature sets.
13093 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13094 const APInt &Zeroable, const X86Subtarget &Subtarget,
13095 SelectionDAG &DAG) {
13096 MVT ExtVT = VT;
13097 MVT EltVT = VT.getVectorElementType();
13098 unsigned NumElts = VT.getVectorNumElements();
13099 unsigned EltBits = VT.getScalarSizeInBits();
13100
13101 if (isSoftF16(EltVT, Subtarget))
13102 return SDValue();
13103
13104 int V2Index =
13105 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13106 Mask.begin();
13107 bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
13108 bool IsV1Zeroable = true;
13109 for (int i = 0, Size = Mask.size(); i < Size; ++i)
13110 if (i != V2Index && !Zeroable[i]) {
13111 IsV1Zeroable = false;
13112 break;
13113 }
13114
13115 // Bail if a non-zero V1 isn't used in place.
13116 if (!IsV1Zeroable) {
13117 SmallVector<int, 8> V1Mask(Mask);
13118 V1Mask[V2Index] = -1;
13119 if (!isNoopShuffleMask(V1Mask))
13120 return SDValue();
13121 }
13122
13123 // Check for a single input from a SCALAR_TO_VECTOR node.
13124 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13125 // all the smarts here sunk into that routine. However, the current
13126 // lowering of BUILD_VECTOR makes that nearly impossible until the old
13127 // vector shuffle lowering is dead.
13128 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13129 DAG);
13130 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13131 // We need to zext the scalar if it is smaller than an i32.
13132 V2S = DAG.getBitcast(EltVT, V2S);
13133 if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
13134 // Using zext to expand a narrow element won't work for non-zero
13135 // insertions. But we can use a masked constant vector if we're
13136 // inserting V2 into the bottom of V1.
13137 if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
13138 return SDValue();
13139
13140 // Zero-extend directly to i32.
13141 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13142 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13143
13144 // If we're inserting into a constant, mask off the inserted index
13145 // and OR with the zero-extended scalar.
13146 if (!IsV1Zeroable) {
13147 SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
13148 Bits[V2Index] = APInt::getZero(EltBits);
13149 SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
13150 V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
13151 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13152 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
13153 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
13154 }
13155 }
13156 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13157 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13158 (EltVT == MVT::i16 && !Subtarget.hasAVX10_2())) {
13159 // Either not inserting from the low element of the input or the input
13160 // element size is too small to use VZEXT_MOVL to clear the high bits.
13161 return SDValue();
13162 }
13163
13164 if (!IsV1Zeroable) {
13165 // If V1 can't be treated as a zero vector we have fewer options to lower
13166 // this. We can't support integer vectors or non-zero targets cheaply.
13167 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13168 if (!VT.isFloatingPoint() || V2Index != 0)
13169 return SDValue();
13170 if (!VT.is128BitVector())
13171 return SDValue();
13172
13173 // Otherwise, use MOVSD, MOVSS or MOVSH.
13174 unsigned MovOpc = 0;
13175 if (EltVT == MVT::f16)
13176 MovOpc = X86ISD::MOVSH;
13177 else if (EltVT == MVT::f32)
13178 MovOpc = X86ISD::MOVSS;
13179 else if (EltVT == MVT::f64)
13180 MovOpc = X86ISD::MOVSD;
13181 else
13182 llvm_unreachable("Unsupported floating point element type to handle!");
13183 return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
13184 }
13185
13186 // This lowering only works for the low element with floating point vectors.
13187 if (VT.isFloatingPoint() && V2Index != 0)
13188 return SDValue();
13189
13190 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13191 if (ExtVT != VT)
13192 V2 = DAG.getBitcast(VT, V2);
13193
13194 if (V2Index != 0) {
13195 // If we have 4 or fewer lanes we can cheaply shuffle the element into
13196 // the desired position. Otherwise it is more efficient to do a vector
13197 // shift left. We know that we can do a vector shift left because all
13198 // the inputs are zero.
13199 if (VT.isFloatingPoint() || NumElts <= 4) {
13200 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13201 V2Shuffle[V2Index] = 0;
13202 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13203 } else {
13204 V2 = DAG.getBitcast(MVT::v16i8, V2);
13205 V2 = DAG.getNode(
13206 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13207 DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
13208 V2 = DAG.getBitcast(VT, V2);
13209 }
13210 }
13211 return V2;
13212}
13213
13214/// Try to lower broadcast of a single - truncated - integer element,
13215/// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13216///
13217/// This assumes we have AVX2.
13219 int BroadcastIdx,
13220 const X86Subtarget &Subtarget,
13221 SelectionDAG &DAG) {
13222 assert(Subtarget.hasAVX2() &&
13223 "We can only lower integer broadcasts with AVX2!");
13224
13225 MVT EltVT = VT.getVectorElementType();
13226 MVT V0VT = V0.getSimpleValueType();
13227
13228 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
13229 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
13230
13231 MVT V0EltVT = V0VT.getVectorElementType();
13232 if (!V0EltVT.isInteger())
13233 return SDValue();
13234
13235 const unsigned EltSize = EltVT.getSizeInBits();
13236 const unsigned V0EltSize = V0EltVT.getSizeInBits();
13237
13238 // This is only a truncation if the original element type is larger.
13239 if (V0EltSize <= EltSize)
13240 return SDValue();
13241
13242 assert(((V0EltSize % EltSize) == 0) &&
13243 "Scalar type sizes must all be powers of 2 on x86!");
13244
13245 const unsigned V0Opc = V0.getOpcode();
13246 const unsigned Scale = V0EltSize / EltSize;
13247 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13248
13249 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13250 V0Opc != ISD::BUILD_VECTOR)
13251 return SDValue();
13252
13253 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13254
13255 // If we're extracting non-least-significant bits, shift so we can truncate.
13256 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13257 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13258 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13259 if (const int OffsetIdx = BroadcastIdx % Scale)
13260 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13261 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13262
13263 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13264 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13265}
13266
13267/// Test whether this can be lowered with a single SHUFPS instruction.
13268///
13269/// This is used to disable more specialized lowerings when the shufps lowering
13270/// will happen to be efficient.
13272 // This routine only handles 128-bit shufps.
13273 assert(Mask.size() == 4 && "Unsupported mask size!");
13274 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
13275 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
13276 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
13277 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
13278
13279 // To lower with a single SHUFPS we need to have the low half and high half
13280 // each requiring a single input.
13281 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13282 return false;
13283 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13284 return false;
13285
13286 return true;
13287}
13288
13289/// Test whether the specified input (0 or 1) is in-place blended by the
13290/// given mask.
13291///
13292/// This returns true if the elements from a particular input are already in the
13293/// slot required by the given mask and require no permutation.
13295 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
13296 int Size = Mask.size();
13297 for (int i = 0; i < Size; ++i)
13298 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
13299 return false;
13300
13301 return true;
13302}
13303
13304/// Test whether the specified input (0 or 1) is a broadcast/splat blended by
13305/// the given mask.
13306///
13308 int BroadcastableElement = 0) {
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 &&
13313 Mask[i] % Size != BroadcastableElement)
13314 return false;
13315 return true;
13316}
13317
13318/// If we are extracting two 128-bit halves of a vector and shuffling the
13319/// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13320/// multi-shuffle lowering.
13322 SDValue N1, ArrayRef<int> Mask,
13323 SelectionDAG &DAG) {
13324 MVT VT = N0.getSimpleValueType();
13325 assert((VT.is128BitVector() &&
13326 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
13327 "VPERM* family of shuffles requires 32-bit or 64-bit elements");
13328
13329 // Check that both sources are extracts of the same source vector.
13330 if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13332 N0.getOperand(0) != N1.getOperand(0) ||
13333 !N0.hasOneUse() || !N1.hasOneUse())
13334 return SDValue();
13335
13336 SDValue WideVec = N0.getOperand(0);
13337 MVT WideVT = WideVec.getSimpleValueType();
13338 if (!WideVT.is256BitVector())
13339 return SDValue();
13340
13341 // Match extracts of each half of the wide source vector. Commute the shuffle
13342 // if the extract of the low half is N1.
13343 unsigned NumElts = VT.getVectorNumElements();
13344 SmallVector<int, 4> NewMask(Mask);
13345 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13346 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13347 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13349 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13350 return SDValue();
13351
13352 // Final bailout: if the mask is simple, we are better off using an extract
13353 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13354 // because that avoids a constant load from memory.
13355 if (NumElts == 4 &&
13356 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
13357 return SDValue();
13358
13359 // Extend the shuffle mask with undef elements.
13360 NewMask.append(NumElts, -1);
13361
13362 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13363 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13364 NewMask);
13365 // This is free: ymm -> xmm.
13366 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13367 DAG.getVectorIdxConstant(0, DL));
13368}
13369
13370/// Try to lower broadcast of a single element.
13371///
13372/// For convenience, this code also bundles all of the subtarget feature set
13373/// filtering. While a little annoying to re-dispatch on type here, there isn't
13374/// a convenient way to factor it out.
13376 SDValue V2, ArrayRef<int> Mask,
13377 const X86Subtarget &Subtarget,
13378 SelectionDAG &DAG) {
13379 MVT EltVT = VT.getVectorElementType();
13380 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13381 (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
13382 (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
13383 return SDValue();
13384
13385 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13386 // we can only broadcast from a register with AVX2.
13387 unsigned NumEltBits = VT.getScalarSizeInBits();
13388 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13389 ? X86ISD::MOVDDUP
13390 : X86ISD::VBROADCAST;
13391 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13392
13393 // Check that the mask is a broadcast.
13394 int BroadcastIdx = getSplatIndex(Mask);
13395 if (BroadcastIdx < 0) {
13396 // Check for hidden broadcast.
13397 SmallVector<int, 16> BroadcastMask(VT.getVectorNumElements(), 0);
13398 if (!isShuffleEquivalent(Mask, BroadcastMask, V1, V2))
13399 return SDValue();
13400 BroadcastIdx = 0;
13401 }
13402 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
13403 "a sorted mask where the broadcast "
13404 "comes from V1.");
13405 int NumActiveElts = count_if(Mask, [](int M) { return M >= 0; });
13406
13407 // Go up the chain of (vector) values to find a scalar load that we can
13408 // combine with the broadcast.
13409 // TODO: Combine this logic with findEltLoadSrc() used by
13410 // EltsFromConsecutiveLoads().
13411 int BitOffset = BroadcastIdx * NumEltBits;
13412 SDValue V = V1;
13413 for (;;) {
13414 switch (V.getOpcode()) {
13415 case ISD::BITCAST: {
13416 V = V.getOperand(0);
13417 continue;
13418 }
13419 case ISD::CONCAT_VECTORS: {
13420 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13421 int OpIdx = BitOffset / OpBitWidth;
13422 V = V.getOperand(OpIdx);
13423 BitOffset %= OpBitWidth;
13424 continue;
13425 }
13427 // The extraction index adds to the existing offset.
13428 unsigned EltBitWidth = V.getScalarValueSizeInBits();
13429 unsigned Idx = V.getConstantOperandVal(1);
13430 unsigned BeginOffset = Idx * EltBitWidth;
13431 BitOffset += BeginOffset;
13432 V = V.getOperand(0);
13433 continue;
13434 }
13435 case ISD::INSERT_SUBVECTOR: {
13436 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13437 int EltBitWidth = VOuter.getScalarValueSizeInBits();
13438 int Idx = (int)V.getConstantOperandVal(2);
13439 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13440 int BeginOffset = Idx * EltBitWidth;
13441 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13442 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13443 BitOffset -= BeginOffset;
13444 V = VInner;
13445 } else {
13446 V = VOuter;
13447 }
13448 continue;
13449 }
13450 }
13451 break;
13452 }
13453 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
13454 BroadcastIdx = BitOffset / NumEltBits;
13455
13456 // Do we need to bitcast the source to retrieve the original broadcast index?
13457 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13458
13459 // Check if this is a broadcast of a scalar. We special case lowering
13460 // for scalars so that we can more effectively fold with loads.
13461 // If the original value has a larger element type than the shuffle, the
13462 // broadcast element is in essence truncated. Make that explicit to ease
13463 // folding.
13464 if (BitCastSrc && VT.isInteger())
13465 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13466 DL, VT, V, BroadcastIdx, Subtarget, DAG))
13467 return TruncBroadcast;
13468
13469 // Also check the simpler case, where we can directly reuse the scalar.
13470 if (!BitCastSrc &&
13471 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13472 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13473 V = V.getOperand(BroadcastIdx);
13474
13475 // If we can't broadcast from a register, check that the input is a load.
13476 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13477 return SDValue();
13478 } else if (ISD::isNormalLoad(V.getNode()) &&
13479 cast<LoadSDNode>(V)->isSimple()) {
13480 // We do not check for one-use of the vector load because a broadcast load
13481 // is expected to be a win for code size, register pressure, and possibly
13482 // uops even if the original vector load is not eliminated.
13483
13484 // Reduce the vector load and shuffle to a broadcasted scalar load.
13485 auto *Ld = cast<LoadSDNode>(V);
13486 SDValue BaseAddr = Ld->getBasePtr();
13487 MVT SVT = VT.getScalarType();
13488 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13489 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
13490 SDValue NewAddr =
13492
13493 // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13494 // than MOVDDUP.
13495 // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13496 if (Opcode == X86ISD::VBROADCAST) {
13497 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13498 SDValue Ops[] = {Ld->getChain(), NewAddr};
13499 V = DAG.getMemIntrinsicNode(
13500 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13502 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13504 return DAG.getBitcast(VT, V);
13505 }
13506 assert(SVT == MVT::f64 && "Unexpected VT!");
13507 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13509 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13511 } else if (!BroadcastFromReg) {
13512 // We can't broadcast from a vector register.
13513 return SDValue();
13514 } else if (BitOffset != 0) {
13515 // We can only broadcast from the zero-element of a vector register,
13516 // but it can be advantageous to broadcast from the zero-element of a
13517 // subvector.
13518 if (!VT.is256BitVector() && !VT.is512BitVector())
13519 return SDValue();
13520
13521 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13522 if (VT == MVT::v4f64 || VT == MVT::v4i64)
13523 return SDValue();
13524
13525 // If we are broadcasting an element from the lowest 128-bit subvector, try
13526 // to move the element in position.
13527 if (BitOffset < 128 && NumActiveElts > 1 &&
13528 V.getScalarValueSizeInBits() == NumEltBits) {
13529 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13530 "Unexpected bit-offset");
13531 SmallVector<int, 16> ExtractMask(128 / NumEltBits, SM_SentinelUndef);
13532 ExtractMask[0] = BitOffset / V.getScalarValueSizeInBits();
13533 V = extractSubVector(V, 0, DAG, DL, 128);
13534 V = DAG.getVectorShuffle(V.getValueType(), DL, V, V, ExtractMask);
13535 } else {
13536 // Only broadcast the zero-element of a 128-bit subvector.
13537 if ((BitOffset % 128) != 0)
13538 return SDValue();
13539
13540 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13541 "Unexpected bit-offset");
13542 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
13543 "Unexpected vector size");
13544 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13545 V = extract128BitVector(V, ExtractIdx, DAG, DL);
13546 }
13547 }
13548
13549 // On AVX we can use VBROADCAST directly for scalar sources.
13550 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
13551 V = DAG.getBitcast(MVT::f64, V);
13552 if (Subtarget.hasAVX()) {
13553 V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
13554 return DAG.getBitcast(VT, V);
13555 }
13556 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
13557 }
13558
13559 // If this is a scalar, do the broadcast on this type and bitcast.
13560 if (!V.getValueType().isVector()) {
13561 assert(V.getScalarValueSizeInBits() == NumEltBits &&
13562 "Unexpected scalar size");
13563 MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13565 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13566 }
13567
13568 // We only support broadcasting from 128-bit vectors to minimize the
13569 // number of patterns we need to deal with in isel. So extract down to
13570 // 128-bits, removing as many bitcasts as possible.
13571 if (V.getValueSizeInBits() > 128)
13573
13574 // Otherwise cast V to a vector with the same element type as VT, but
13575 // possibly narrower than VT. Then perform the broadcast.
13576 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13577 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13578 return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13579}
13580
13581// Check for whether we can use INSERTPS to perform the shuffle. We only use
13582// INSERTPS when the V1 elements are already in the correct locations
13583// because otherwise we can just always use two SHUFPS instructions which
13584// are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13585// perform INSERTPS if a single V1 element is out of place and all V2
13586// elements are zeroable.
13588 unsigned &InsertPSMask,
13589 const APInt &Zeroable,
13590 ArrayRef<int> Mask, SelectionDAG &DAG) {
13591 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
13592 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
13593 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13594
13595 // Attempt to match INSERTPS with one element from VA or VB being
13596 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13597 // are updated.
13598 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13599 ArrayRef<int> CandidateMask) {
13600 unsigned ZMask = 0;
13601 int VADstIndex = -1;
13602 int VBDstIndex = -1;
13603 bool VAUsedInPlace = false;
13604
13605 for (int i = 0; i < 4; ++i) {
13606 // Synthesize a zero mask from the zeroable elements (includes undefs).
13607 if (Zeroable[i]) {
13608 ZMask |= 1 << i;
13609 continue;
13610 }
13611
13612 // Flag if we use any VA inputs in place.
13613 if (i == CandidateMask[i]) {
13614 VAUsedInPlace = true;
13615 continue;
13616 }
13617
13618 // We can only insert a single non-zeroable element.
13619 if (VADstIndex >= 0 || VBDstIndex >= 0)
13620 return false;
13621
13622 if (CandidateMask[i] < 4) {
13623 // VA input out of place for insertion.
13624 VADstIndex = i;
13625 } else {
13626 // VB input for insertion.
13627 VBDstIndex = i;
13628 }
13629 }
13630
13631 // Don't bother if we have no (non-zeroable) element for insertion.
13632 if (VADstIndex < 0 && VBDstIndex < 0)
13633 return false;
13634
13635 // Determine element insertion src/dst indices. The src index is from the
13636 // start of the inserted vector, not the start of the concatenated vector.
13637 unsigned VBSrcIndex = 0;
13638 if (VADstIndex >= 0) {
13639 // If we have a VA input out of place, we use VA as the V2 element
13640 // insertion and don't use the original V2 at all.
13641 VBSrcIndex = CandidateMask[VADstIndex];
13642 VBDstIndex = VADstIndex;
13643 VB = VA;
13644 } else {
13645 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13646 }
13647
13648 // If no V1 inputs are used in place, then the result is created only from
13649 // the zero mask and the V2 insertion - so remove V1 dependency.
13650 if (!VAUsedInPlace)
13651 VA = DAG.getUNDEF(MVT::v4f32);
13652
13653 // Update V1, V2 and InsertPSMask accordingly.
13654 V1 = VA;
13655 V2 = VB;
13656
13657 // Insert the V2 element into the desired position.
13658 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13659 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
13660 return true;
13661 };
13662
13663 if (matchAsInsertPS(V1, V2, Mask))
13664 return true;
13665
13666 // Commute and try again.
13667 SmallVector<int, 4> CommutedMask(Mask);
13669 if (matchAsInsertPS(V2, V1, CommutedMask))
13670 return true;
13671
13672 return false;
13673}
13674
13676 ArrayRef<int> Mask, const APInt &Zeroable,
13677 SelectionDAG &DAG) {
13678 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13679 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13680
13681 // Attempt to match the insertps pattern.
13682 unsigned InsertPSMask = 0;
13683 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13684 return SDValue();
13685
13686 // Insert the V2 element into the desired position.
13687 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13688 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13689}
13690
13691/// Handle lowering of 2-lane 64-bit floating point shuffles.
13692///
13693/// This is the basis function for the 2-lane 64-bit shuffles as we have full
13694/// support for floating point shuffles but not integer shuffles. These
13695/// instructions will incur a domain crossing penalty on some chips though so
13696/// it is better to avoid lowering through this for integer vectors where
13697/// possible.
13699 const APInt &Zeroable, SDValue V1, SDValue V2,
13700 const X86Subtarget &Subtarget,
13701 SelectionDAG &DAG) {
13702 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13703 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13704 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13705
13706 if (V2.isUndef()) {
13707 // Check for being able to broadcast a single element.
13708 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13709 Mask, Subtarget, DAG))
13710 return Broadcast;
13711
13712 // Straight shuffle of a single input vector. Simulate this by using the
13713 // single input as both of the "inputs" to this instruction..
13714 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13715
13716 if (Subtarget.hasAVX()) {
13717 // If we have AVX, we can use VPERMILPS which will allow folding a load
13718 // into the shuffle.
13719 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13720 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13721 }
13722
13723 return DAG.getNode(
13724 X86ISD::SHUFP, DL, MVT::v2f64,
13725 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13726 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13727 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13728 }
13729 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13730 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13731 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13732 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13733
13734 if (Subtarget.hasAVX2())
13735 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13736 return Extract;
13737
13738 // When loading a scalar and then shuffling it into a vector we can often do
13739 // the insertion cheaply.
13741 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13742 return Insertion;
13743 // Try inverting the insertion since for v2 masks it is easy to do and we
13744 // can't reliably sort the mask one way or the other.
13745 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13746 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13748 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13749 return Insertion;
13750
13751 // Try to use one of the special instruction patterns to handle two common
13752 // blend patterns if a zero-blend above didn't work.
13753 if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
13754 isShuffleEquivalent(Mask, {1, 3}, V1, V2))
13755 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13756 // We can either use a special instruction to load over the low double or
13757 // to move just the low double.
13758 return DAG.getNode(
13759 X86ISD::MOVSD, DL, MVT::v2f64, V2,
13760 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13761
13762 if (Subtarget.hasSSE41())
13763 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13764 Zeroable, Subtarget, DAG))
13765 return Blend;
13766
13767 // Use dedicated unpack instructions for masks that match their pattern.
13768 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, V1, V2, Mask, DAG))
13769 return V;
13770
13771 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13772 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13773 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13774}
13775
13776/// Handle lowering of 2-lane 64-bit integer shuffles.
13777///
13778/// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13779/// the integer unit to minimize domain crossing penalties. However, for blends
13780/// it falls back to the floating point shuffle operation with appropriate bit
13781/// casting.
13783 const APInt &Zeroable, SDValue V1, SDValue V2,
13784 const X86Subtarget &Subtarget,
13785 SelectionDAG &DAG) {
13786 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13787 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13788 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13789
13790 if (V2.isUndef()) {
13791 // Check for being able to broadcast a single element.
13792 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13793 Mask, Subtarget, DAG))
13794 return Broadcast;
13795
13796 // Straight shuffle of a single input vector. For everything from SSE2
13797 // onward this has a single fast instruction with no scary immediates.
13798 // We have to map the mask as it is actually a v4i32 shuffle instruction.
13799 V1 = DAG.getBitcast(MVT::v4i32, V1);
13800 int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
13801 Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
13802 Mask[1] < 0 ? -1 : (Mask[1] * 2),
13803 Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
13804 return DAG.getBitcast(
13805 MVT::v2i64,
13806 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13807 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13808 }
13809 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13810 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13811 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13812 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13813
13814 if (Subtarget.hasAVX2())
13815 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13816 return Extract;
13817
13818 // Try to use shift instructions.
13819 if (SDValue Shift =
13820 lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
13821 DAG, /*BitwiseOnly*/ false))
13822 return Shift;
13823
13824 // When loading a scalar and then shuffling it into a vector we can often do
13825 // the insertion cheaply.
13827 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13828 return Insertion;
13829 // Try inverting the insertion since for v2 masks it is easy to do and we
13830 // can't reliably sort the mask one way or the other.
13831 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13833 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13834 return Insertion;
13835
13836 // We have different paths for blend lowering, but they all must use the
13837 // *exact* same predicate.
13838 bool IsBlendSupported = Subtarget.hasSSE41();
13839 if (IsBlendSupported)
13840 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13841 Zeroable, Subtarget, DAG))
13842 return Blend;
13843
13844 // Use dedicated unpack instructions for masks that match their pattern.
13845 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, V1, V2, Mask, DAG))
13846 return V;
13847
13848 // Try to use byte rotation instructions.
13849 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13850 if (Subtarget.hasSSSE3()) {
13851 if (Subtarget.hasVLX())
13852 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
13853 Zeroable, Subtarget, DAG))
13854 return Rotate;
13855
13856 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13857 Subtarget, DAG))
13858 return Rotate;
13859 }
13860
13861 // If we have direct support for blends, we should lower by decomposing into
13862 // a permute. That will be faster than the domain cross.
13863 if (IsBlendSupported)
13864 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
13865 Zeroable, Subtarget, DAG);
13866
13867 // We implement this with SHUFPD which is pretty lame because it will likely
13868 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13869 // However, all the alternatives are still more cycles and newer chips don't
13870 // have this problem. It would be really nice if x86 had better shuffles here.
13871 V1 = DAG.getBitcast(MVT::v2f64, V1);
13872 V2 = DAG.getBitcast(MVT::v2f64, V2);
13873 return DAG.getBitcast(MVT::v2i64,
13874 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13875}
13876
13877/// Lower a vector shuffle using the SHUFPS instruction.
13878///
13879/// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13880/// It makes no assumptions about whether this is the *best* lowering, it simply
13881/// uses it.
13883 ArrayRef<int> Mask, SDValue V1,
13884 SDValue V2, SelectionDAG &DAG) {
13885 SDValue LowV = V1, HighV = V2;
13886 SmallVector<int, 4> NewMask(Mask);
13887 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13888
13889 if (NumV2Elements == 1) {
13890 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13891
13892 // Compute the index adjacent to V2Index and in the same half by toggling
13893 // the low bit.
13894 int V2AdjIndex = V2Index ^ 1;
13895
13896 if (Mask[V2AdjIndex] < 0) {
13897 // Handles all the cases where we have a single V2 element and an undef.
13898 // This will only ever happen in the high lanes because we commute the
13899 // vector otherwise.
13900 if (V2Index < 2)
13901 std::swap(LowV, HighV);
13902 NewMask[V2Index] -= 4;
13903 } else {
13904 // Handle the case where the V2 element ends up adjacent to a V1 element.
13905 // To make this work, blend them together as the first step.
13906 int V1Index = V2AdjIndex;
13907 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13908 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13909 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13910
13911 // Now proceed to reconstruct the final blend as we have the necessary
13912 // high or low half formed.
13913 if (V2Index < 2) {
13914 LowV = V2;
13915 HighV = V1;
13916 } else {
13917 HighV = V2;
13918 }
13919 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13920 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13921 }
13922 } else if (NumV2Elements == 2) {
13923 if (Mask[0] < 4 && Mask[1] < 4) {
13924 // Handle the easy case where we have V1 in the low lanes and V2 in the
13925 // high lanes.
13926 NewMask[2] -= 4;
13927 NewMask[3] -= 4;
13928 } else if (Mask[2] < 4 && Mask[3] < 4) {
13929 // We also handle the reversed case because this utility may get called
13930 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13931 // arrange things in the right direction.
13932 NewMask[0] -= 4;
13933 NewMask[1] -= 4;
13934 HighV = V1;
13935 LowV = V2;
13936 } else {
13937 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13938 // trying to place elements directly, just blend them and set up the final
13939 // shuffle to place them.
13940
13941 // The first two blend mask elements are for V1, the second two are for
13942 // V2.
13943 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13944 Mask[2] < 4 ? Mask[2] : Mask[3],
13945 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13946 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13947 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13948 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13949
13950 // Now we do a normal shuffle of V1 by giving V1 as both operands to
13951 // a blend.
13952 LowV = HighV = V1;
13953 NewMask[0] = Mask[0] < 4 ? 0 : 2;
13954 NewMask[1] = Mask[0] < 4 ? 2 : 0;
13955 NewMask[2] = Mask[2] < 4 ? 1 : 3;
13956 NewMask[3] = Mask[2] < 4 ? 3 : 1;
13957 }
13958 } else if (NumV2Elements == 3) {
13959 // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
13960 // we can get here due to other paths (e.g repeated mask matching) that we
13961 // don't want to do another round of lowerVECTOR_SHUFFLE.
13963 return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
13964 }
13965 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13966 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13967}
13968
13969/// Lower 4-lane 32-bit floating point shuffles.
13970///
13971/// Uses instructions exclusively from the floating point unit to minimize
13972/// domain crossing penalties, as these are sufficient to implement all v4f32
13973/// shuffles.
13975 const APInt &Zeroable, SDValue V1, SDValue V2,
13976 const X86Subtarget &Subtarget,
13977 SelectionDAG &DAG) {
13978 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13979 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13980 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13981
13982 if (Subtarget.hasSSE41())
13983 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13984 Zeroable, Subtarget, DAG))
13985 return Blend;
13986
13987 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13988
13989 if (NumV2Elements == 0) {
13990 // Check for being able to broadcast a single element.
13991 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
13992 Mask, Subtarget, DAG))
13993 return Broadcast;
13994
13995 // Use even/odd duplicate instructions for masks that match their pattern.
13996 if (Subtarget.hasSSE3()) {
13997 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
13998 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
13999 if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
14000 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
14001 }
14002
14003 if (Subtarget.hasAVX()) {
14004 // If we have AVX, we can use VPERMILPS which will allow folding a load
14005 // into the shuffle.
14006 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
14007 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14008 }
14009
14010 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
14011 // in SSE1 because otherwise they are widened to v2f64 and never get here.
14012 if (!Subtarget.hasSSE2()) {
14013 if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14014 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14015 if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14016 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14017 }
14018
14019 // Otherwise, use a straight shuffle of a single input vector. We pass the
14020 // input vector to both operands to simulate this with a SHUFPS.
14021 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14022 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14023 }
14024
14025 if (Subtarget.hasSSE2())
14027 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
14028 ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
14029 return ZExt;
14030 }
14031
14032 if (Subtarget.hasAVX2())
14033 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14034 return Extract;
14035
14036 // There are special ways we can lower some single-element blends. However, we
14037 // have custom ways we can lower more complex single-element blends below that
14038 // we defer to if both this and BLENDPS fail to match, so restrict this to
14039 // when the V2 input is targeting element 0 of the mask -- that is the fast
14040 // case here.
14041 if (NumV2Elements == 1 && Mask[0] >= 4)
14042 if (SDValue V = lowerShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2, Mask,
14043 Zeroable, Subtarget, DAG))
14044 return V;
14045
14046 if (Subtarget.hasSSE41()) {
14047 bool MatchesShufPS = isSingleSHUFPSMask(Mask);
14048
14049 // Use INSERTPS if we can complete the shuffle efficiently.
14050 if (!MatchesShufPS || Zeroable == 0x3 || Zeroable == 0xC)
14051 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14052 return V;
14053
14054 if (!MatchesShufPS)
14055 if (SDValue BlendPerm =
14056 lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1, V2, Mask, DAG))
14057 return BlendPerm;
14058 }
14059
14060 // Use low/high mov instructions. These are only valid in SSE1 because
14061 // otherwise they are widened to v2f64 and never get here.
14062 if (!Subtarget.hasSSE2()) {
14063 if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14064 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14065 if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14066 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14067 }
14068
14069 // Use dedicated unpack instructions for masks that match their pattern.
14070 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, V1, V2, Mask, DAG))
14071 return V;
14072
14073 // Otherwise fall back to a SHUFPS lowering strategy.
14074 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14075}
14076
14077/// Lower 4-lane i32 vector shuffles.
14078///
14079/// We try to handle these with integer-domain shuffles where we can, but for
14080/// blends we use the floating point domain blend instructions.
14082 const APInt &Zeroable, SDValue V1, SDValue V2,
14083 const X86Subtarget &Subtarget,
14084 SelectionDAG &DAG) {
14085 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14086 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14087 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14088
14089 // Whenever we can lower this as a zext, that instruction is strictly faster
14090 // than any alternative. It also allows us to fold memory operands into the
14091 // shuffle in many cases.
14092 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14093 Zeroable, Subtarget, DAG))
14094 return ZExt;
14095
14096 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14097
14098 // Try to use shift instructions if fast.
14099 if (Subtarget.preferLowerShuffleAsShift()) {
14100 if (SDValue Shift =
14101 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
14102 Subtarget, DAG, /*BitwiseOnly*/ true))
14103 return Shift;
14104 if (NumV2Elements == 0)
14105 if (SDValue Rotate =
14106 lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
14107 return Rotate;
14108 }
14109
14110 if (NumV2Elements == 0) {
14111 // Try to use broadcast unless the mask only has one non-undef element.
14112 if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14113 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14114 Mask, Subtarget, DAG))
14115 return Broadcast;
14116 }
14117
14118 // Straight shuffle of a single input vector. For everything from SSE2
14119 // onward this has a single fast instruction with no scary immediates.
14120 // We coerce the shuffle pattern to be compatible with UNPCK instructions
14121 // but we aren't actually going to use the UNPCK instruction because doing
14122 // so prevents folding a load into this instruction or making a copy.
14123 const int UnpackLoMask[] = {0, 0, 1, 1};
14124 const int UnpackHiMask[] = {2, 2, 3, 3};
14125 if (!isSingleElementRepeatedMask(Mask)) {
14126 if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14127 Mask = UnpackLoMask;
14128 else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14129 Mask = UnpackHiMask;
14130 }
14131
14132 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14133 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14134 }
14135
14136 if (Subtarget.hasAVX2())
14137 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14138 return Extract;
14139
14140 // Try to use shift instructions.
14141 if (SDValue Shift =
14142 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
14143 DAG, /*BitwiseOnly*/ false))
14144 return Shift;
14145
14146 // There are special ways we can lower some single-element blends.
14147 if (NumV2Elements == 1)
14149 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14150 return V;
14151
14152 // We have different paths for blend lowering, but they all must use the
14153 // *exact* same predicate.
14154 bool IsBlendSupported = Subtarget.hasSSE41();
14155 if (IsBlendSupported)
14156 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14157 Zeroable, Subtarget, DAG))
14158 return Blend;
14159
14160 if (SDValue Masked =
14161 lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, Zeroable, DAG))
14162 return Masked;
14163
14164 // Use dedicated unpack instructions for masks that match their pattern.
14165 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, V1, V2, Mask, DAG))
14166 return V;
14167
14168 // Try to use byte rotation instructions.
14169 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14170 if (Subtarget.hasSSSE3()) {
14171 if (Subtarget.hasVLX())
14172 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14173 Zeroable, Subtarget, DAG))
14174 return Rotate;
14175
14176 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14177 Subtarget, DAG))
14178 return Rotate;
14179 }
14180
14181 // Assume that a single SHUFPS is faster than an alternative sequence of
14182 // multiple instructions (even if the CPU has a domain penalty).
14183 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14184 if (!isSingleSHUFPSMask(Mask)) {
14185 // If we have direct support for blends, we should lower by decomposing into
14186 // a permute. That will be faster than the domain cross.
14187 if (IsBlendSupported)
14188 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
14189 Zeroable, Subtarget, DAG);
14190
14191 // Try to lower by permuting the inputs into an unpack instruction.
14192 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14193 Mask, Subtarget, DAG))
14194 return Unpack;
14195 }
14196
14197 // We implement this with SHUFPS because it can blend from two vectors.
14198 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14199 // up the inputs, bypassing domain shift penalties that we would incur if we
14200 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14201 // relevant.
14202 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14203 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14204 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14205 return DAG.getBitcast(MVT::v4i32, ShufPS);
14206}
14207
14208/// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14209/// shuffle lowering, and the most complex part.
14210///
14211/// The lowering strategy is to try to form pairs of input lanes which are
14212/// targeted at the same half of the final vector, and then use a dword shuffle
14213/// to place them onto the right half, and finally unpack the paired lanes into
14214/// their final position.
14215///
14216/// The exact breakdown of how to form these dword pairs and align them on the
14217/// correct sides is really tricky. See the comments within the function for
14218/// more of the details.
14219///
14220/// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14221/// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14222/// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14223/// vector, form the analogous 128-bit 8-element Mask.
14225 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14226 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14227 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
14228 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14229
14230 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
14231 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14232 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14233
14234 // Attempt to directly match PSHUFLW or PSHUFHW.
14235 if (isUndefOrInRange(LoMask, 0, 4) &&
14236 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14237 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14238 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14239 }
14240 if (isUndefOrInRange(HiMask, 4, 8) &&
14241 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14242 for (int i = 0; i != 4; ++i)
14243 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14244 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14245 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14246 }
14247
14248 SmallVector<int, 4> LoInputs;
14249 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14250 array_pod_sort(LoInputs.begin(), LoInputs.end());
14251 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
14252 SmallVector<int, 4> HiInputs;
14253 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14254 array_pod_sort(HiInputs.begin(), HiInputs.end());
14255 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
14256 int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14257 int NumHToL = LoInputs.size() - NumLToL;
14258 int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14259 int NumHToH = HiInputs.size() - NumLToH;
14260 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14261 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14262 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14263 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14264
14265 // If we are shuffling values from one half - check how many different DWORD
14266 // pairs we need to create. If only 1 or 2 then we can perform this as a
14267 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14268 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14269 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14270 V = DAG.getNode(ShufWOp, DL, VT, V,
14271 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14272 V = DAG.getBitcast(PSHUFDVT, V);
14273 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14274 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14275 return DAG.getBitcast(VT, V);
14276 };
14277
14278 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14279 int PSHUFDMask[4] = { -1, -1, -1, -1 };
14280 SmallVector<std::pair<int, int>, 4> DWordPairs;
14281 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14282
14283 // Collect the different DWORD pairs.
14284 for (int DWord = 0; DWord != 4; ++DWord) {
14285 int M0 = Mask[2 * DWord + 0];
14286 int M1 = Mask[2 * DWord + 1];
14287 M0 = (M0 >= 0 ? M0 % 4 : M0);
14288 M1 = (M1 >= 0 ? M1 % 4 : M1);
14289 if (M0 < 0 && M1 < 0)
14290 continue;
14291
14292 bool Match = false;
14293 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14294 auto &DWordPair = DWordPairs[j];
14295 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14296 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14297 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14298 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14299 PSHUFDMask[DWord] = DOffset + j;
14300 Match = true;
14301 break;
14302 }
14303 }
14304 if (!Match) {
14305 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14306 DWordPairs.push_back(std::make_pair(M0, M1));
14307 }
14308 }
14309
14310 if (DWordPairs.size() <= 2) {
14311 DWordPairs.resize(2, std::make_pair(-1, -1));
14312 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14313 DWordPairs[1].first, DWordPairs[1].second};
14314 // For splat, ensure we widen the PSHUFDMask to allow vXi64 folds.
14315 if (ShuffleVectorSDNode::isSplatMask(PSHUFDMask) &&
14316 ShuffleVectorSDNode::isSplatMask(PSHUFHalfMask)) {
14317 int SplatIdx = ShuffleVectorSDNode::getSplatMaskIndex(PSHUFHalfMask);
14318 std::fill(PSHUFHalfMask, PSHUFHalfMask + 4, SplatIdx);
14319 PSHUFDMask[0] = PSHUFDMask[2] = DOffset + 0;
14320 PSHUFDMask[1] = PSHUFDMask[3] = DOffset + 1;
14321 }
14322 if ((NumHToL + NumHToH) == 0)
14323 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14324 if ((NumLToL + NumLToH) == 0)
14325 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14326 }
14327 }
14328
14329 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14330 // such inputs we can swap two of the dwords across the half mark and end up
14331 // with <=2 inputs to each half in each half. Once there, we can fall through
14332 // to the generic code below. For example:
14333 //
14334 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14335 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14336 //
14337 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14338 // and an existing 2-into-2 on the other half. In this case we may have to
14339 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14340 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14341 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14342 // because any other situation (including a 3-into-1 or 1-into-3 in the other
14343 // half than the one we target for fixing) will be fixed when we re-enter this
14344 // path. We will also combine away any sequence of PSHUFD instructions that
14345 // result into a single instruction. Here is an example of the tricky case:
14346 //
14347 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14348 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14349 //
14350 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14351 //
14352 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14353 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14354 //
14355 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14356 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14357 //
14358 // The result is fine to be handled by the generic logic.
14359 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14360 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14361 int AOffset, int BOffset) {
14362 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
14363 "Must call this with A having 3 or 1 inputs from the A half.");
14364 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
14365 "Must call this with B having 1 or 3 inputs from the B half.");
14366 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
14367 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
14368
14369 bool ThreeAInputs = AToAInputs.size() == 3;
14370
14371 // Compute the index of dword with only one word among the three inputs in
14372 // a half by taking the sum of the half with three inputs and subtracting
14373 // the sum of the actual three inputs. The difference is the remaining
14374 // slot.
14375 int ADWord = 0, BDWord = 0;
14376 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14377 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14378 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14379 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14380 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14381 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14382 int TripleNonInputIdx =
14383 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14384 TripleDWord = TripleNonInputIdx / 2;
14385
14386 // We use xor with one to compute the adjacent DWord to whichever one the
14387 // OneInput is in.
14388 OneInputDWord = (OneInput / 2) ^ 1;
14389
14390 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14391 // and BToA inputs. If there is also such a problem with the BToB and AToB
14392 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14393 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14394 // is essential that we don't *create* a 3<-1 as then we might oscillate.
14395 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14396 // Compute how many inputs will be flipped by swapping these DWords. We
14397 // need
14398 // to balance this to ensure we don't form a 3-1 shuffle in the other
14399 // half.
14400 int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
14401 llvm::count(AToBInputs, 2 * ADWord + 1);
14402 int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
14403 llvm::count(BToBInputs, 2 * BDWord + 1);
14404 if ((NumFlippedAToBInputs == 1 &&
14405 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14406 (NumFlippedBToBInputs == 1 &&
14407 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14408 // We choose whether to fix the A half or B half based on whether that
14409 // half has zero flipped inputs. At zero, we may not be able to fix it
14410 // with that half. We also bias towards fixing the B half because that
14411 // will more commonly be the high half, and we have to bias one way.
14412 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14413 ArrayRef<int> Inputs) {
14414 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14415 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14416 // Determine whether the free index is in the flipped dword or the
14417 // unflipped dword based on where the pinned index is. We use this bit
14418 // in an xor to conditionally select the adjacent dword.
14419 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14420 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14421 if (IsFixIdxInput == IsFixFreeIdxInput)
14422 FixFreeIdx += 1;
14423 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14424 assert(IsFixIdxInput != IsFixFreeIdxInput &&
14425 "We need to be changing the number of flipped inputs!");
14426 int PSHUFHalfMask[] = {0, 1, 2, 3};
14427 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14428 V = DAG.getNode(
14429 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14430 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14431 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14432
14433 for (int &M : Mask)
14434 if (M >= 0 && M == FixIdx)
14435 M = FixFreeIdx;
14436 else if (M >= 0 && M == FixFreeIdx)
14437 M = FixIdx;
14438 };
14439 if (NumFlippedBToBInputs != 0) {
14440 int BPinnedIdx =
14441 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14442 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14443 } else {
14444 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
14445 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14446 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14447 }
14448 }
14449 }
14450
14451 int PSHUFDMask[] = {0, 1, 2, 3};
14452 PSHUFDMask[ADWord] = BDWord;
14453 PSHUFDMask[BDWord] = ADWord;
14454 V = DAG.getBitcast(
14455 VT,
14456 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14457 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14458
14459 // Adjust the mask to match the new locations of A and B.
14460 for (int &M : Mask)
14461 if (M >= 0 && M/2 == ADWord)
14462 M = 2 * BDWord + M % 2;
14463 else if (M >= 0 && M/2 == BDWord)
14464 M = 2 * ADWord + M % 2;
14465
14466 // Recurse back into this routine to re-compute state now that this isn't
14467 // a 3 and 1 problem.
14468 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14469 };
14470 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14471 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14472 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14473 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14474
14475 // At this point there are at most two inputs to the low and high halves from
14476 // each half. That means the inputs can always be grouped into dwords and
14477 // those dwords can then be moved to the correct half with a dword shuffle.
14478 // We use at most one low and one high word shuffle to collect these paired
14479 // inputs into dwords, and finally a dword shuffle to place them.
14480 int PSHUFLMask[4] = {-1, -1, -1, -1};
14481 int PSHUFHMask[4] = {-1, -1, -1, -1};
14482 int PSHUFDMask[4] = {-1, -1, -1, -1};
14483
14484 // First fix the masks for all the inputs that are staying in their
14485 // original halves. This will then dictate the targets of the cross-half
14486 // shuffles.
14487 auto fixInPlaceInputs =
14488 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14489 MutableArrayRef<int> SourceHalfMask,
14490 MutableArrayRef<int> HalfMask, int HalfOffset) {
14491 if (InPlaceInputs.empty())
14492 return;
14493 if (InPlaceInputs.size() == 1) {
14494 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14495 InPlaceInputs[0] - HalfOffset;
14496 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14497 return;
14498 }
14499 if (IncomingInputs.empty()) {
14500 // Just fix all of the in place inputs.
14501 for (int Input : InPlaceInputs) {
14502 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14503 PSHUFDMask[Input / 2] = Input / 2;
14504 }
14505 return;
14506 }
14507
14508 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
14509 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14510 InPlaceInputs[0] - HalfOffset;
14511 // Put the second input next to the first so that they are packed into
14512 // a dword. We find the adjacent index by toggling the low bit.
14513 int AdjIndex = InPlaceInputs[0] ^ 1;
14514 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14515 llvm::replace(HalfMask, InPlaceInputs[1], AdjIndex);
14516 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14517 };
14518 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14519 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14520
14521 // Now gather the cross-half inputs and place them into a free dword of
14522 // their target half.
14523 // FIXME: This operation could almost certainly be simplified dramatically to
14524 // look more like the 3-1 fixing operation.
14525 auto moveInputsToRightHalf = [&PSHUFDMask](
14526 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14527 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14528 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14529 int DestOffset) {
14530 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14531 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14532 };
14533 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14534 int Word) {
14535 int LowWord = Word & ~1;
14536 int HighWord = Word | 1;
14537 return isWordClobbered(SourceHalfMask, LowWord) ||
14538 isWordClobbered(SourceHalfMask, HighWord);
14539 };
14540
14541 if (IncomingInputs.empty())
14542 return;
14543
14544 if (ExistingInputs.empty()) {
14545 // Map any dwords with inputs from them into the right half.
14546 for (int Input : IncomingInputs) {
14547 // If the source half mask maps over the inputs, turn those into
14548 // swaps and use the swapped lane.
14549 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14550 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14551 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14552 Input - SourceOffset;
14553 // We have to swap the uses in our half mask in one sweep.
14554 for (int &M : HalfMask)
14555 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14556 M = Input;
14557 else if (M == Input)
14558 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14559 } else {
14560 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
14561 Input - SourceOffset &&
14562 "Previous placement doesn't match!");
14563 }
14564 // Note that this correctly re-maps both when we do a swap and when
14565 // we observe the other side of the swap above. We rely on that to
14566 // avoid swapping the members of the input list directly.
14567 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14568 }
14569
14570 // Map the input's dword into the correct half.
14571 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14572 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14573 else
14574 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
14575 Input / 2 &&
14576 "Previous placement doesn't match!");
14577 }
14578
14579 // And just directly shift any other-half mask elements to be same-half
14580 // as we will have mirrored the dword containing the element into the
14581 // same position within that half.
14582 for (int &M : HalfMask)
14583 if (M >= SourceOffset && M < SourceOffset + 4) {
14584 M = M - SourceOffset + DestOffset;
14585 assert(M >= 0 && "This should never wrap below zero!");
14586 }
14587 return;
14588 }
14589
14590 // Ensure we have the input in a viable dword of its current half. This
14591 // is particularly tricky because the original position may be clobbered
14592 // by inputs being moved and *staying* in that half.
14593 if (IncomingInputs.size() == 1) {
14594 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14595 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14596 SourceOffset;
14597 SourceHalfMask[InputFixed - SourceOffset] =
14598 IncomingInputs[0] - SourceOffset;
14599 llvm::replace(HalfMask, IncomingInputs[0], InputFixed);
14600 IncomingInputs[0] = InputFixed;
14601 }
14602 } else if (IncomingInputs.size() == 2) {
14603 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14604 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14605 // We have two non-adjacent or clobbered inputs we need to extract from
14606 // the source half. To do this, we need to map them into some adjacent
14607 // dword slot in the source mask.
14608 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14609 IncomingInputs[1] - SourceOffset};
14610
14611 // If there is a free slot in the source half mask adjacent to one of
14612 // the inputs, place the other input in it. We use (Index XOR 1) to
14613 // compute an adjacent index.
14614 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14615 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14616 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14617 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14618 InputsFixed[1] = InputsFixed[0] ^ 1;
14619 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14620 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14621 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14622 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14623 InputsFixed[0] = InputsFixed[1] ^ 1;
14624 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14625 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14626 // The two inputs are in the same DWord but it is clobbered and the
14627 // adjacent DWord isn't used at all. Move both inputs to the free
14628 // slot.
14629 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14630 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14631 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14632 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14633 } else {
14634 // The only way we hit this point is if there is no clobbering
14635 // (because there are no off-half inputs to this half) and there is no
14636 // free slot adjacent to one of the inputs. In this case, we have to
14637 // swap an input with a non-input.
14638 for (int i = 0; i < 4; ++i)
14639 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14640 "We can't handle any clobbers here!");
14641 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14642 "Cannot have adjacent inputs here!");
14643
14644 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14645 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14646
14647 // We also have to update the final source mask in this case because
14648 // it may need to undo the above swap.
14649 for (int &M : FinalSourceHalfMask)
14650 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14651 M = InputsFixed[1] + SourceOffset;
14652 else if (M == InputsFixed[1] + SourceOffset)
14653 M = (InputsFixed[0] ^ 1) + SourceOffset;
14654
14655 InputsFixed[1] = InputsFixed[0] ^ 1;
14656 }
14657
14658 // Point everything at the fixed inputs.
14659 for (int &M : HalfMask)
14660 if (M == IncomingInputs[0])
14661 M = InputsFixed[0] + SourceOffset;
14662 else if (M == IncomingInputs[1])
14663 M = InputsFixed[1] + SourceOffset;
14664
14665 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14666 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14667 }
14668 } else {
14669 llvm_unreachable("Unhandled input size!");
14670 }
14671
14672 // Now hoist the DWord down to the right half.
14673 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14674 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14675 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14676 for (int &M : HalfMask)
14677 for (int Input : IncomingInputs)
14678 if (M == Input)
14679 M = FreeDWord * 2 + Input % 2;
14680 };
14681 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14682 /*SourceOffset*/ 4, /*DestOffset*/ 0);
14683 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14684 /*SourceOffset*/ 0, /*DestOffset*/ 4);
14685
14686 // Now enact all the shuffles we've computed to move the inputs into their
14687 // target half.
14688 if (!isNoopShuffleMask(PSHUFLMask))
14689 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14690 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14691 if (!isNoopShuffleMask(PSHUFHMask))
14692 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14693 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14694 if (!isNoopShuffleMask(PSHUFDMask))
14695 V = DAG.getBitcast(
14696 VT,
14697 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14698 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14699
14700 // At this point, each half should contain all its inputs, and we can then
14701 // just shuffle them into their final position.
14702 assert(none_of(LoMask, [](int M) { return M >= 4; }) &&
14703 "Failed to lift all the high half inputs to the low mask!");
14704 assert(none_of(HiMask, [](int M) { return M >= 0 && M < 4; }) &&
14705 "Failed to lift all the low half inputs to the high mask!");
14706
14707 // Do a half shuffle for the low mask.
14708 if (!isNoopShuffleMask(LoMask))
14709 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14710 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14711
14712 // Do a half shuffle with the high mask after shifting its values down.
14713 for (int &M : HiMask)
14714 if (M >= 0)
14715 M -= 4;
14716 if (!isNoopShuffleMask(HiMask))
14717 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14718 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14719
14720 return V;
14721}
14722
14723/// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14724/// blend if only one input is used.
14726 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14727 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14729 "Lane crossing shuffle masks not supported");
14730
14731 int NumBytes = VT.getSizeInBits() / 8;
14732 int Size = Mask.size();
14733 int Scale = NumBytes / Size;
14734
14735 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14736 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14737 V1InUse = false;
14738 V2InUse = false;
14739
14740 for (int i = 0; i < NumBytes; ++i) {
14741 int M = Mask[i / Scale];
14742 if (M < 0)
14743 continue;
14744
14745 const int ZeroMask = 0x80;
14746 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14747 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14748 if (Zeroable[i / Scale])
14749 V1Idx = V2Idx = ZeroMask;
14750
14751 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14752 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14753 V1InUse |= (ZeroMask != V1Idx);
14754 V2InUse |= (ZeroMask != V2Idx);
14755 }
14756
14757 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14758 if (V1InUse)
14759 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14760 DAG.getBuildVector(ShufVT, DL, V1Mask));
14761 if (V2InUse)
14762 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14763 DAG.getBuildVector(ShufVT, DL, V2Mask));
14764
14765 // If we need shuffled inputs from both, blend the two.
14766 SDValue V;
14767 if (V1InUse && V2InUse)
14768 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14769 else
14770 V = V1InUse ? V1 : V2;
14771
14772 // Cast the result back to the correct type.
14773 return DAG.getBitcast(VT, V);
14774}
14775
14776/// Generic lowering of 8-lane i16 shuffles.
14777///
14778/// This handles both single-input shuffles and combined shuffle/blends with
14779/// two inputs. The single input shuffles are immediately delegated to
14780/// a dedicated lowering routine.
14781///
14782/// The blends are lowered in one of three fundamental ways. If there are few
14783/// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14784/// of the input is significantly cheaper when lowered as an interleaving of
14785/// the two inputs, try to interleave them. Otherwise, blend the low and high
14786/// halves of the inputs separately (making them have relatively few inputs)
14787/// and then concatenate them.
14789 const APInt &Zeroable, SDValue V1, SDValue V2,
14790 const X86Subtarget &Subtarget,
14791 SelectionDAG &DAG) {
14792 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14793 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14794 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14795
14796 // Whenever we can lower this as a zext, that instruction is strictly faster
14797 // than any alternative.
14798 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14799 Zeroable, Subtarget, DAG))
14800 return ZExt;
14801
14802 // Try to use lower using a truncation.
14803 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14804 Subtarget, DAG))
14805 return V;
14806
14807 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14808
14809 if (NumV2Inputs == 0) {
14810 // Try to use shift instructions.
14811 if (SDValue Shift =
14812 lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
14813 Subtarget, DAG, /*BitwiseOnly*/ false))
14814 return Shift;
14815
14816 // Check for being able to broadcast a single element.
14817 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14818 Mask, Subtarget, DAG))
14819 return Broadcast;
14820
14821 // Try to use bit rotation instructions.
14822 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
14823 Subtarget, DAG))
14824 return Rotate;
14825
14826 // Use dedicated unpack instructions for masks that match their pattern.
14827 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14828 return V;
14829
14830 // Use dedicated pack instructions for masks that match their pattern.
14831 if (SDValue V =
14832 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14833 return V;
14834
14835 // Try to use byte rotation instructions.
14836 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14837 Subtarget, DAG))
14838 return Rotate;
14839
14840 // Make a copy of the mask so it can be modified.
14841 SmallVector<int, 8> MutableMask(Mask);
14842 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14843 Subtarget, DAG);
14844 }
14845
14846 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14847 "All single-input shuffles should be canonicalized to be V1-input "
14848 "shuffles.");
14849
14850 // Try to use shift instructions.
14851 if (SDValue Shift =
14852 lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
14853 DAG, /*BitwiseOnly*/ false))
14854 return Shift;
14855
14856 // See if we can use SSE4A Extraction / Insertion.
14857 if (Subtarget.hasSSE4A())
14858 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14859 Zeroable, DAG))
14860 return V;
14861
14862 // There are special ways we can lower some single-element blends.
14863 if (NumV2Inputs == 1)
14865 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14866 return V;
14867
14868 // We have different paths for blend lowering, but they all must use the
14869 // *exact* same predicate.
14870 bool IsBlendSupported = Subtarget.hasSSE41();
14871 if (IsBlendSupported)
14872 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14873 Zeroable, Subtarget, DAG))
14874 return Blend;
14875
14876 if (SDValue Masked =
14877 lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, Zeroable, DAG))
14878 return Masked;
14879
14880 // Use dedicated unpack instructions for masks that match their pattern.
14881 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14882 return V;
14883
14884 // Use dedicated pack instructions for masks that match their pattern.
14885 if (SDValue V =
14886 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14887 return V;
14888
14889 // Try to use lower using a truncation.
14890 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14891 Subtarget, DAG))
14892 return V;
14893
14894 // Try to use byte rotation instructions.
14895 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14896 Subtarget, DAG))
14897 return Rotate;
14898
14899 if (SDValue BitBlend =
14900 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14901 return BitBlend;
14902
14903 // Try to use byte shift instructions to mask.
14904 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14905 Zeroable, Subtarget, DAG))
14906 return V;
14907
14908 // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
14909 int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
14910 if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
14911 !Subtarget.hasVLX()) {
14912 // Check if this is part of a 256-bit vector truncation.
14913 unsigned PackOpc = 0;
14914 if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
14916 peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
14917 SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
14918 V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
14919 getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
14920 DAG.getTargetConstant(0xEE, DL, MVT::i8));
14921 V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
14922 V1 = extract128BitVector(V1V2, 0, DAG, DL);
14923 V2 = extract128BitVector(V1V2, 4, DAG, DL);
14924 PackOpc = X86ISD::PACKUS;
14925 } else if (Subtarget.hasSSE41()) {
14926 SmallVector<SDValue, 4> DWordClearOps(4,
14927 DAG.getConstant(0, DL, MVT::i32));
14928 for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
14929 DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
14930 SDValue DWordClearMask =
14931 DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
14932 V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
14933 DWordClearMask);
14934 V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
14935 DWordClearMask);
14936 PackOpc = X86ISD::PACKUS;
14937 } else if (!Subtarget.hasSSSE3()) {
14938 SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
14939 V1 = DAG.getBitcast(MVT::v4i32, V1);
14940 V2 = DAG.getBitcast(MVT::v4i32, V2);
14941 V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
14942 V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
14943 V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
14944 V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
14945 PackOpc = X86ISD::PACKSS;
14946 }
14947 if (PackOpc) {
14948 // Now pack things back together.
14949 SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
14950 if (NumEvenDrops == 2) {
14951 Result = DAG.getBitcast(MVT::v4i32, Result);
14952 Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
14953 }
14954 return Result;
14955 }
14956 }
14957
14958 // When compacting odd (upper) elements, use PACKSS pre-SSE41.
14959 int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
14960 if (NumOddDrops == 1) {
14961 bool HasSSE41 = Subtarget.hasSSE41();
14962 V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14963 DAG.getBitcast(MVT::v4i32, V1),
14964 DAG.getTargetConstant(16, DL, MVT::i8));
14965 V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14966 DAG.getBitcast(MVT::v4i32, V2),
14967 DAG.getTargetConstant(16, DL, MVT::i8));
14968 return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
14969 MVT::v8i16, V1, V2);
14970 }
14971
14972 // Try to lower by permuting the inputs into an unpack instruction.
14973 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14974 Mask, Subtarget, DAG))
14975 return Unpack;
14976
14977 // If we can't directly blend but can use PSHUFB, that will be better as it
14978 // can both shuffle and set up the inefficient blend.
14979 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14980 bool V1InUse, V2InUse;
14981 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14982 Zeroable, DAG, V1InUse, V2InUse);
14983 }
14984
14985 // We can always bit-blend if we have to so the fallback strategy is to
14986 // decompose into single-input permutes and blends/unpacks.
14987 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2, Mask,
14988 Zeroable, Subtarget, DAG);
14989}
14990
14991/// Lower 8-lane 16-bit floating point shuffles.
14993 const APInt &Zeroable, SDValue V1, SDValue V2,
14994 const X86Subtarget &Subtarget,
14995 SelectionDAG &DAG) {
14996 assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14997 assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14998 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14999 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
15000
15001 if (Subtarget.hasFP16()) {
15002 if (NumV2Elements == 0) {
15003 // Check for being able to broadcast a single element.
15004 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
15005 Mask, Subtarget, DAG))
15006 return Broadcast;
15007 }
15008 if (NumV2Elements == 1 && Mask[0] >= 8)
15010 DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15011 return V;
15012 }
15013
15014 V1 = DAG.getBitcast(MVT::v8i16, V1);
15015 V2 = DAG.getBitcast(MVT::v8i16, V2);
15016 return DAG.getBitcast(MVT::v8f16,
15017 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15018}
15019
15020// Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15021// sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15022// the active subvector is extracted.
15024 ArrayRef<int> OriginalMask, SDValue V1,
15025 SDValue V2, const X86Subtarget &Subtarget,
15026 SelectionDAG &DAG) {
15027 // Commute binary inputs so V2 is a load to simplify VPERMI2/T2 folds.
15028 SmallVector<int, 32> Mask(OriginalMask);
15029 if (!V2.isUndef() && isShuffleFoldableLoad(V1) &&
15030 !isShuffleFoldableLoad(V2)) {
15032 std::swap(V1, V2);
15033 }
15034
15035 MVT MaskVT = VT.changeTypeToInteger();
15036 SDValue MaskNode;
15037 MVT ShuffleVT = VT;
15038 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15039 V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15040 V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15041 ShuffleVT = V1.getSimpleValueType();
15042
15043 // Adjust mask to correct indices for the second input.
15044 int NumElts = VT.getVectorNumElements();
15045 unsigned Scale = 512 / VT.getSizeInBits();
15046 SmallVector<int, 32> AdjustedMask(Mask);
15047 for (int &M : AdjustedMask)
15048 if (NumElts <= M)
15049 M += (Scale - 1) * NumElts;
15050 MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15051 MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15052 } else {
15053 MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15054 }
15055
15056 SDValue Result;
15057 if (V2.isUndef())
15058 Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15059 else
15060 Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15061
15062 if (VT != ShuffleVT)
15063 Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15064
15065 return Result;
15066}
15067
15068/// Generic lowering of v16i8 shuffles.
15069///
15070/// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15071/// detect any complexity reducing interleaving. If that doesn't help, it uses
15072/// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15073/// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15074/// back together.
15076 const APInt &Zeroable, SDValue V1, SDValue V2,
15077 const X86Subtarget &Subtarget,
15078 SelectionDAG &DAG) {
15079 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15080 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15081 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15082
15083 // Try to use shift instructions.
15084 if (SDValue Shift =
15085 lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
15086 DAG, /*BitwiseOnly*/ false))
15087 return Shift;
15088
15089 // Try to use byte rotation instructions.
15090 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15091 Subtarget, DAG))
15092 return Rotate;
15093
15094 // Use dedicated pack instructions for masks that match their pattern.
15095 if (SDValue V =
15096 lowerShuffleWithPACK(DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15097 return V;
15098
15099 // Try to use a zext lowering.
15100 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15101 Zeroable, Subtarget, DAG))
15102 return ZExt;
15103
15104 // Try to use lower using a truncation.
15105 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15106 Subtarget, DAG))
15107 return V;
15108
15109 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15110 Subtarget, DAG))
15111 return V;
15112
15113 // See if we can use SSE4A Extraction / Insertion.
15114 if (Subtarget.hasSSE4A())
15115 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15116 Zeroable, DAG))
15117 return V;
15118
15119 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15120
15121 // For single-input shuffles, there are some nicer lowering tricks we can use.
15122 if (NumV2Elements == 0) {
15123 // Check for being able to broadcast a single element.
15124 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15125 Mask, Subtarget, DAG))
15126 return Broadcast;
15127
15128 // Try to use bit rotation instructions.
15129 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15130 Subtarget, DAG))
15131 return Rotate;
15132
15133 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15134 return V;
15135
15136 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15137 // Notably, this handles splat and partial-splat shuffles more efficiently.
15138 // However, it only makes sense if the pre-duplication shuffle simplifies
15139 // things significantly. Currently, this means we need to be able to
15140 // express the pre-duplication shuffle as an i16 shuffle.
15141 //
15142 // FIXME: We should check for other patterns which can be widened into an
15143 // i16 shuffle as well.
15144 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15145 for (int i = 0; i < 16; i += 2)
15146 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15147 return false;
15148
15149 return true;
15150 };
15151 auto tryToWidenViaDuplication = [&]() -> SDValue {
15152 if (!canWidenViaDuplication(Mask))
15153 return SDValue();
15154 SmallVector<int, 4> LoInputs;
15155 copy_if(Mask, std::back_inserter(LoInputs),
15156 [](int M) { return M >= 0 && M < 8; });
15157 array_pod_sort(LoInputs.begin(), LoInputs.end());
15158 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
15159 SmallVector<int, 4> HiInputs;
15160 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15161 array_pod_sort(HiInputs.begin(), HiInputs.end());
15162 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
15163
15164 bool TargetLo = LoInputs.size() >= HiInputs.size();
15165 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15166 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15167
15168 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15170 for (int I : InPlaceInputs) {
15171 PreDupI16Shuffle[I/2] = I/2;
15172 LaneMap[I] = I;
15173 }
15174 int j = TargetLo ? 0 : 4, je = j + 4;
15175 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15176 // Check if j is already a shuffle of this input. This happens when
15177 // there are two adjacent bytes after we move the low one.
15178 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15179 // If we haven't yet mapped the input, search for a slot into which
15180 // we can map it.
15181 while (j < je && PreDupI16Shuffle[j] >= 0)
15182 ++j;
15183
15184 if (j == je)
15185 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15186 return SDValue();
15187
15188 // Map this input with the i16 shuffle.
15189 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15190 }
15191
15192 // Update the lane map based on the mapping we ended up with.
15193 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15194 }
15195 V1 = DAG.getBitcast(
15196 MVT::v16i8,
15197 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15198 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15199
15200 // Unpack the bytes to form the i16s that will be shuffled into place.
15201 bool EvenInUse = false, OddInUse = false;
15202 for (int i = 0; i < 16; i += 2) {
15203 EvenInUse |= (Mask[i + 0] >= 0);
15204 OddInUse |= (Mask[i + 1] >= 0);
15205 if (EvenInUse && OddInUse)
15206 break;
15207 }
15208 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15209 MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15210 OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15211
15212 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15213 for (int i = 0; i < 16; ++i)
15214 if (Mask[i] >= 0) {
15215 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15216 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
15217 if (PostDupI16Shuffle[i / 2] < 0)
15218 PostDupI16Shuffle[i / 2] = MappedMask;
15219 else
15220 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
15221 "Conflicting entries in the original shuffle!");
15222 }
15223 return DAG.getBitcast(
15224 MVT::v16i8,
15225 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15226 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
15227 };
15228 if (SDValue V = tryToWidenViaDuplication())
15229 return V;
15230 }
15231
15232 if (SDValue Masked =
15233 lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG))
15234 return Masked;
15235
15236 // Use dedicated unpack instructions for masks that match their pattern.
15237 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15238 return V;
15239
15240 // Try to use byte shift instructions to mask.
15241 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15242 Zeroable, Subtarget, DAG))
15243 return V;
15244
15245 // Check for compaction patterns.
15246 bool IsSingleInput = V2.isUndef();
15247 int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
15248
15249 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15250 // with PSHUFB. It is important to do this before we attempt to generate any
15251 // blends but after all of the single-input lowerings. If the single input
15252 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15253 // want to preserve that and we can DAG combine any longer sequences into
15254 // a PSHUFB in the end. But once we start blending from multiple inputs,
15255 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15256 // and there are *very* few patterns that would actually be faster than the
15257 // PSHUFB approach because of its ability to zero lanes.
15258 //
15259 // If the mask is a binary compaction, we can more efficiently perform this
15260 // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15261 //
15262 // FIXME: The only exceptions to the above are blends which are exact
15263 // interleavings with direct instructions supporting them. We currently don't
15264 // handle those well here.
15265 if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15266 bool V1InUse = false;
15267 bool V2InUse = false;
15268
15270 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15271
15272 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15273 // do so. This avoids using them to handle blends-with-zero which is
15274 // important as a single pshufb is significantly faster for that.
15275 if (V1InUse && V2InUse) {
15276 if (Subtarget.hasSSE41())
15277 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15278 Zeroable, Subtarget, DAG))
15279 return Blend;
15280
15281 // We can use an unpack to do the blending rather than an or in some
15282 // cases. Even though the or may be (very minorly) more efficient, we
15283 // preference this lowering because there are common cases where part of
15284 // the complexity of the shuffles goes away when we do the final blend as
15285 // an unpack.
15286 // FIXME: It might be worth trying to detect if the unpack-feeding
15287 // shuffles will both be pshufb, in which case we shouldn't bother with
15288 // this.
15290 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15291 return Unpack;
15292
15293 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
15294 if (Subtarget.hasVBMI())
15295 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
15296 DAG);
15297
15298 // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
15299 if (Subtarget.hasXOP()) {
15300 SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
15301 return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
15302 }
15303
15304 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15305 // PALIGNR will be cheaper than the second PSHUFB+OR.
15307 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15308 return V;
15309 }
15310
15311 return PSHUFB;
15312 }
15313
15314 // There are special ways we can lower some single-element blends.
15315 if (NumV2Elements == 1)
15317 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15318 return V;
15319
15320 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15321 return Blend;
15322
15323 // Check whether a compaction lowering can be done. This handles shuffles
15324 // which take every Nth element for some even N. See the helper function for
15325 // details.
15326 //
15327 // We special case these as they can be particularly efficiently handled with
15328 // the PACKUSB instruction on x86 and they show up in common patterns of
15329 // rearranging bytes to truncate wide elements.
15330 if (NumEvenDrops) {
15331 // NumEvenDrops is the power of two stride of the elements. Another way of
15332 // thinking about it is that we need to drop the even elements this many
15333 // times to get the original input.
15334
15335 // First we need to zero all the dropped bytes.
15336 assert(NumEvenDrops <= 3 &&
15337 "No support for dropping even elements more than 3 times.");
15338 SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15339 for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15340 WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15341 SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15342 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15343 WordClearMask);
15344 if (!IsSingleInput)
15345 V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15346 WordClearMask);
15347
15348 // Now pack things back together.
15349 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15350 IsSingleInput ? V1 : V2);
15351 for (int i = 1; i < NumEvenDrops; ++i) {
15352 Result = DAG.getBitcast(MVT::v8i16, Result);
15353 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15354 }
15355 return Result;
15356 }
15357
15358 int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
15359 if (NumOddDrops == 1) {
15360 V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15361 DAG.getBitcast(MVT::v8i16, V1),
15362 DAG.getTargetConstant(8, DL, MVT::i8));
15363 if (!IsSingleInput)
15364 V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15365 DAG.getBitcast(MVT::v8i16, V2),
15366 DAG.getTargetConstant(8, DL, MVT::i8));
15367 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15368 IsSingleInput ? V1 : V2);
15369 }
15370
15371 // Handle multi-input cases by blending/unpacking single-input shuffles.
15372 if (NumV2Elements > 0)
15373 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
15374 Zeroable, Subtarget, DAG);
15375
15376 // The fallback path for single-input shuffles widens this into two v8i16
15377 // vectors with unpacks, shuffles those, and then pulls them back together
15378 // with a pack.
15379 SDValue V = V1;
15380
15381 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15382 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15383 for (int i = 0; i < 16; ++i)
15384 if (Mask[i] >= 0)
15385 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15386
15387 SDValue VLoHalf, VHiHalf;
15388 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15389 // them out and avoid using UNPCK{L,H} to extract the elements of V as
15390 // i16s.
15391 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15392 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15393 // Use a mask to drop the high bytes.
15394 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15395 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15396 DAG.getConstant(0x00FF, DL, MVT::v8i16));
15397
15398 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15399 VHiHalf = DAG.getUNDEF(MVT::v8i16);
15400
15401 // Squash the masks to point directly into VLoHalf.
15402 for (int &M : LoBlendMask)
15403 if (M >= 0)
15404 M /= 2;
15405 for (int &M : HiBlendMask)
15406 if (M >= 0)
15407 M /= 2;
15408 } else {
15409 // Otherwise just unpack the low half of V into VLoHalf and the high half into
15410 // VHiHalf so that we can blend them as i16s.
15411 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15412
15413 VLoHalf = DAG.getBitcast(
15414 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15415 VHiHalf = DAG.getBitcast(
15416 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15417 }
15418
15419 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15420 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15421
15422 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15423}
15424
15425/// Dispatching routine to lower various 128-bit x86 vector shuffles.
15426///
15427/// This routine breaks down the specific type of 128-bit shuffle and
15428/// dispatches to the lowering routines accordingly.
15430 MVT VT, SDValue V1, SDValue V2,
15431 const APInt &Zeroable,
15432 const X86Subtarget &Subtarget,
15433 SelectionDAG &DAG) {
15434 if (VT == MVT::v8bf16) {
15435 V1 = DAG.getBitcast(MVT::v8i16, V1);
15436 V2 = DAG.getBitcast(MVT::v8i16, V2);
15437 return DAG.getBitcast(VT,
15438 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15439 }
15440
15441 switch (VT.SimpleTy) {
15442 case MVT::v2i64:
15443 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15444 case MVT::v2f64:
15445 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15446 case MVT::v4i32:
15447 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15448 case MVT::v4f32:
15449 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15450 case MVT::v8i16:
15451 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15452 case MVT::v8f16:
15453 return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15454 case MVT::v16i8:
15455 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15456
15457 default:
15458 llvm_unreachable("Unimplemented!");
15459 }
15460}
15461
15462/// Generic routine to split vector shuffle into half-sized shuffles.
15463///
15464/// This routine just extracts two subvectors, shuffles them independently, and
15465/// then concatenates them back together. This should work effectively with all
15466/// AVX vector shuffle types.
15468 SDValue V2, ArrayRef<int> Mask,
15469 SelectionDAG &DAG, bool SimpleOnly) {
15470 assert(VT.getSizeInBits() >= 256 &&
15471 "Only for 256-bit or wider vector shuffles!");
15472 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
15473 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
15474
15475 // If this came from the AVX1 v8i32 -> v8f32 bitcast, split using v4i32.
15476 if (VT == MVT::v8f32) {
15478 SDValue BC2 = peekThroughBitcasts(V2);
15479 if (BC1.getValueType() == MVT::v8i32 && BC2.getValueType() == MVT::v8i32) {
15480 if (SDValue Split = splitAndLowerShuffle(DL, MVT::v8i32, BC1, BC2, Mask,
15481 DAG, SimpleOnly))
15482 return DAG.getBitcast(VT, Split);
15483 }
15484 }
15485
15486 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15487 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15488
15489 int NumElements = VT.getVectorNumElements();
15490 int SplitNumElements = NumElements / 2;
15491 MVT ScalarVT = VT.getVectorElementType();
15492 MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15493
15494 // Use splitVector/extractSubVector so that split build-vectors just build two
15495 // narrower build vectors. This helps shuffling with splats and zeros.
15496 auto SplitVector = [&](SDValue V) {
15497 SDValue LoV, HiV;
15498 std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15499 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15500 DAG.getBitcast(SplitVT, HiV));
15501 };
15502
15503 SDValue LoV1, HiV1, LoV2, HiV2;
15504 std::tie(LoV1, HiV1) = SplitVector(V1);
15505 std::tie(LoV2, HiV2) = SplitVector(V2);
15506
15507 // Now create two 4-way blends of these half-width vectors.
15508 auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
15509 bool &UseHiV1, bool &UseLoV2,
15510 bool &UseHiV2) {
15511 UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
15512 for (int i = 0; i < SplitNumElements; ++i) {
15513 int M = HalfMask[i];
15514 if (M >= NumElements) {
15515 if (M >= NumElements + SplitNumElements)
15516 UseHiV2 = true;
15517 else
15518 UseLoV2 = true;
15519 } else if (M >= 0) {
15520 if (M >= SplitNumElements)
15521 UseHiV1 = true;
15522 else
15523 UseLoV1 = true;
15524 }
15525 }
15526 };
15527
15528 auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
15529 if (!SimpleOnly)
15530 return true;
15531
15532 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15533 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15534
15535 return !(UseHiV1 || UseHiV2);
15536 };
15537
15538 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15539 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15540 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15541 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15542 for (int i = 0; i < SplitNumElements; ++i) {
15543 int M = HalfMask[i];
15544 if (M >= NumElements) {
15545 V2BlendMask[i] = M - NumElements;
15546 BlendMask[i] = SplitNumElements + i;
15547 } else if (M >= 0) {
15548 V1BlendMask[i] = M;
15549 BlendMask[i] = i;
15550 }
15551 }
15552
15553 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15554 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15555
15556 // Because the lowering happens after all combining takes place, we need to
15557 // manually combine these blend masks as much as possible so that we create
15558 // a minimal number of high-level vector shuffle nodes.
15559 assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
15560
15561 // First try just blending the halves of V1 or V2.
15562 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15563 return DAG.getUNDEF(SplitVT);
15564 if (!UseLoV2 && !UseHiV2)
15565 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15566 if (!UseLoV1 && !UseHiV1)
15567 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15568
15569 SDValue V1Blend, V2Blend;
15570 if (UseLoV1 && UseHiV1) {
15571 V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15572 } else {
15573 // We only use half of V1 so map the usage down into the final blend mask.
15574 V1Blend = UseLoV1 ? LoV1 : HiV1;
15575 for (int i = 0; i < SplitNumElements; ++i)
15576 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15577 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15578 }
15579 if (UseLoV2 && UseHiV2) {
15580 V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15581 } else {
15582 // We only use half of V2 so map the usage down into the final blend mask.
15583 V2Blend = UseLoV2 ? LoV2 : HiV2;
15584 for (int i = 0; i < SplitNumElements; ++i)
15585 if (BlendMask[i] >= SplitNumElements)
15586 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15587 }
15588 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15589 };
15590
15591 if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
15592 return SDValue();
15593
15594 SDValue Lo = HalfBlend(LoMask);
15595 SDValue Hi = HalfBlend(HiMask);
15596 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15597}
15598
15599/// Either split a vector in halves or decompose the shuffles and the
15600/// blend/unpack.
15601///
15602/// This is provided as a good fallback for many lowerings of non-single-input
15603/// shuffles with more than one 128-bit lane. In those cases, we want to select
15604/// between splitting the shuffle into 128-bit components and stitching those
15605/// back together vs. extracting the single-input shuffles and blending those
15606/// results.
15608 SDValue V2, ArrayRef<int> Mask,
15609 const APInt &Zeroable,
15610 const X86Subtarget &Subtarget,
15611 SelectionDAG &DAG) {
15612 assert(!V2.isUndef() && "This routine must not be used to lower single-input "
15613 "shuffles as it could then recurse on itself.");
15614 int Size = Mask.size();
15615
15616 // If this can be modeled as a broadcast of two elements followed by a blend,
15617 // prefer that lowering. This is especially important because broadcasts can
15618 // often fold with memory operands.
15619 auto DoBothBroadcast = [&] {
15620 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15621 for (int M : Mask)
15622 if (M >= Size) {
15623 if (V2BroadcastIdx < 0)
15624 V2BroadcastIdx = M - Size;
15625 else if ((M - Size) != V2BroadcastIdx &&
15626 !IsElementEquivalent(Size, V2, V2, M - Size, V2BroadcastIdx))
15627 return false;
15628 } else if (M >= 0) {
15629 if (V1BroadcastIdx < 0)
15630 V1BroadcastIdx = M;
15631 else if (M != V1BroadcastIdx &&
15632 !IsElementEquivalent(Size, V1, V1, M, V1BroadcastIdx))
15633 return false;
15634 }
15635 return true;
15636 };
15637 if (DoBothBroadcast())
15638 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15639 Subtarget, DAG);
15640
15641 // If the inputs all stem from a single 128-bit lane of each input, then we
15642 // split them rather than blending because the split will decompose to
15643 // unusually few instructions.
15644 int LaneCount = VT.getSizeInBits() / 128;
15645 int LaneSize = Size / LaneCount;
15646 SmallBitVector LaneInputs[2];
15647 LaneInputs[0].resize(LaneCount, false);
15648 LaneInputs[1].resize(LaneCount, false);
15649 for (int i = 0; i < Size; ++i)
15650 if (Mask[i] >= 0)
15651 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15652 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15653 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15654 /*SimpleOnly*/ false);
15655
15656 // Without AVX2, if we can freely split the subvectors then we're better off
15657 // performing half width shuffles.
15658 if (!Subtarget.hasAVX2()) {
15660 SDValue BC2 = peekThroughBitcasts(V2);
15661 bool SplatOrSplitV1 = isFreeToSplitVector(BC1, DAG) ||
15662 DAG.isSplatValue(BC1, /*AllowUndefs=*/true);
15663 bool SplatOrSplitV2 = isFreeToSplitVector(BC2, DAG) ||
15664 DAG.isSplatValue(BC2, /*AllowUndefs=*/true);
15665 if (SplatOrSplitV1 && SplatOrSplitV2)
15666 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15667 /*SimpleOnly*/ false);
15668 }
15669
15670 // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
15671 // requires that the decomposed single-input shuffles don't end up here.
15672 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15673 Subtarget, DAG);
15674}
15675
15676// Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15677// TODO: Extend to support v8f32 (+ 512-bit shuffles).
15679 SDValue V1, SDValue V2,
15680 ArrayRef<int> Mask,
15681 SelectionDAG &DAG) {
15682 assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
15683
15684 int LHSMask[4] = {-1, -1, -1, -1};
15685 int RHSMask[4] = {-1, -1, -1, -1};
15686 int SHUFPDMask[4] = {-1, -1, -1, -1};
15687
15688 // As SHUFPD uses a single LHS/RHS element per lane, we can always
15689 // perform the shuffle once the lanes have been shuffled in place.
15690 for (int i = 0; i != 4; ++i) {
15691 int M = Mask[i];
15692 if (M < 0)
15693 continue;
15694 int LaneBase = i & ~1;
15695 auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15696 LaneMask[LaneBase + (M & 1)] = M;
15697 SHUFPDMask[i] = M & 1;
15698 }
15699
15700 SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15701 SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15702 return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15703 getSHUFPDImmForMask(SHUFPDMask, DL, DAG));
15704}
15705
15706/// Lower a vector shuffle crossing multiple 128-bit lanes as
15707/// a lane permutation followed by a per-lane permutation.
15708///
15709/// This is mainly for cases where we can have non-repeating permutes
15710/// in each lane.
15711///
15712/// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15713/// we should investigate merging them.
15715 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15716 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15717 int NumElts = VT.getVectorNumElements();
15718 int NumLanes = VT.getSizeInBits() / 128;
15719 int NumEltsPerLane = NumElts / NumLanes;
15720 bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
15721
15722 /// Attempts to find a sublane permute with the given size
15723 /// that gets all elements into their target lanes.
15724 ///
15725 /// Returns a decomposed shuffle, or an empty SDValue if none is found.
15726 /// SameMask is set to true when the cross-lane mask reproduces Mask. Callers
15727 /// must then stop trying smaller sublane sizes to avoid a legalization cycle.
15728 auto getSublanePermute = [&](int NumSublanes, bool &SameMask) -> SDValue {
15729 int NumSublanesPerLane = NumSublanes / NumLanes;
15730 int NumEltsPerSublane = NumElts / NumSublanes;
15731
15732 SmallVector<int, 16> CrossLaneMask;
15733 SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
15734 // CrossLaneMask but one entry == one sublane.
15735 SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
15736 APInt DemandedCrossLane = APInt::getZero(NumElts);
15737
15738 for (int i = 0; i != NumElts; ++i) {
15739 int M = Mask[i];
15740 if (M < 0)
15741 continue;
15742
15743 int SrcSublane = M / NumEltsPerSublane;
15744 int DstLane = i / NumEltsPerLane;
15745
15746 // We only need to get the elements into the right lane, not sublane.
15747 // So search all sublanes that make up the destination lane.
15748 bool Found = false;
15749 int DstSubStart = DstLane * NumSublanesPerLane;
15750 int DstSubEnd = DstSubStart + NumSublanesPerLane;
15751 for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
15752 if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
15753 continue;
15754
15755 Found = true;
15756 CrossLaneMaskLarge[DstSublane] = SrcSublane;
15757 int DstSublaneOffset = DstSublane * NumEltsPerSublane;
15758 InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
15759 DemandedCrossLane.setBit(InLaneMask[i]);
15760 break;
15761 }
15762 if (!Found)
15763 return SDValue();
15764 }
15765
15766 // Fill CrossLaneMask using CrossLaneMaskLarge.
15767 narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15768
15769 if (!CanUseSublanes) {
15770 // If we're only shuffling a single lowest lane and the rest are identity
15771 // then don't bother.
15772 // TODO - isShuffleMaskInputInPlace could be extended to something like
15773 // this.
15774 int NumIdentityLanes = 0;
15775 bool OnlyShuffleLowestLane = true;
15776 for (int i = 0; i != NumLanes; ++i) {
15777 int LaneOffset = i * NumEltsPerLane;
15778 if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15779 i * NumEltsPerLane))
15780 NumIdentityLanes++;
15781 else if (CrossLaneMask[LaneOffset] != 0)
15782 OnlyShuffleLowestLane = false;
15783 }
15784 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15785 return SDValue();
15786 }
15787
15788 // Simplify CrossLaneMask based on the actual demanded elements.
15789 if (V1.hasOneUse())
15790 for (int i = 0; i != NumElts; ++i)
15791 if (!DemandedCrossLane[i])
15792 CrossLaneMask[i] = SM_SentinelUndef;
15793
15794 // Avoid returning the same shuffle operation. For example,
15795 // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
15796 // undef:v16i16
15797 if (CrossLaneMask == Mask) {
15798 // Trying another sublane size could bring us back to this shuffle,
15799 // causing an infinite loop during legalization.
15800 SameMask = true;
15801 return SDValue();
15802 }
15803 if (InLaneMask == Mask)
15804 return SDValue();
15805
15806 SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15807 return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15808 InLaneMask);
15809 };
15810
15811 // Try 128-bit lanes first. If that fails, try 64-bit and then 32-bit
15812 // sublanes, if supported.
15813 int MaxSublaneScale = 1;
15814 if (CanUseSublanes)
15815 MaxSublaneScale = Subtarget.hasFastVariableCrossLaneShuffle() ? 4 : 2;
15816
15817 for (int SublaneScale = 1; SublaneScale <= MaxSublaneScale;
15818 SublaneScale *= 2) {
15819 bool SameMask = false;
15820 if (SDValue V = getSublanePermute(
15821 /*NumSublanes=*/NumLanes * SublaneScale, SameMask))
15822 return V;
15823 if (SameMask)
15824 return SDValue();
15825 }
15826 return SDValue();
15827}
15828
15829/// Helper to get compute inlane shuffle mask for a complete shuffle mask.
15830static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
15831 SmallVector<int> &InLaneMask) {
15832 int Size = Mask.size();
15833 InLaneMask.assign(Mask.begin(), Mask.end());
15834 for (int i = 0; i < Size; ++i) {
15835 int &M = InLaneMask[i];
15836 if (M < 0)
15837 continue;
15838 if (((M % Size) / LaneSize) != (i / LaneSize))
15839 M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15840 }
15841}
15842
15843/// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15844/// source with a lane permutation.
15845///
15846/// This lowering strategy results in four instructions in the worst case for a
15847/// single-input cross lane shuffle which is lower than any other fully general
15848/// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15849/// shuffle pattern should be handled prior to trying this lowering.
15851 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15852 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15853 // FIXME: This should probably be generalized for 512-bit vectors as well.
15854 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15855 int Size = Mask.size();
15856 int LaneSize = Size / 2;
15857
15858 // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15859 // Only do this if the elements aren't all from the lower lane,
15860 // otherwise we're (probably) better off doing a split.
15861 if (VT == MVT::v4f64 &&
15862 !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15863 return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
15864
15865 // If there are only inputs from one 128-bit lane, splitting will in fact be
15866 // less expensive. The flags track whether the given lane contains an element
15867 // that crosses to another lane.
15868 bool AllLanes;
15869 if (!Subtarget.hasAVX2()) {
15870 bool LaneCrossing[2] = {false, false};
15871 for (int i = 0; i < Size; ++i)
15872 if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15873 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15874 AllLanes = LaneCrossing[0] && LaneCrossing[1];
15875 } else {
15876 bool LaneUsed[2] = {false, false};
15877 for (int i = 0; i < Size; ++i)
15878 if (Mask[i] >= 0)
15879 LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15880 AllLanes = LaneUsed[0] && LaneUsed[1];
15881 }
15882
15883 // TODO - we could support shuffling V2 in the Flipped input.
15884 assert(V2.isUndef() &&
15885 "This last part of this routine only works on single input shuffles");
15886
15887 SmallVector<int> InLaneMask;
15888 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
15889
15890 assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15891 "In-lane shuffle mask expected");
15892
15893 // If we're not using both lanes in each lane and the inlane mask is not
15894 // repeating, then we're better off splitting.
15895 if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
15896 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15897 /*SimpleOnly*/ false);
15898
15899 // Flip the lanes, and shuffle the results which should now be in-lane.
15900 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15901 SDValue Flipped = DAG.getBitcast(PVT, V1);
15902 Flipped =
15903 DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15904 Flipped = DAG.getBitcast(VT, Flipped);
15905 return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15906}
15907
15908/// Handle lowering 2-lane 128-bit shuffles.
15910 SDValue V2, ArrayRef<int> Mask,
15911 const APInt &Zeroable,
15912 const X86Subtarget &Subtarget,
15913 SelectionDAG &DAG) {
15914 if (V2.isUndef()) {
15915 // Attempt to match VBROADCAST*128 subvector broadcast load.
15916 bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
15917 bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
15918 if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
15920 MVT MemVT = VT.getHalfNumVectorElementsVT();
15921 unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
15923 if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
15924 VT, MemVT, Ld, Ofs, DAG))
15925 return BcstLd;
15926 }
15927
15928 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15929 if (Subtarget.hasAVX2())
15930 return SDValue();
15931 }
15932
15933 bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15934
15935 SmallVector<int, 4> WidenedMask;
15936 if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15937 return SDValue();
15938
15939 bool IsLowZero = (Zeroable & 0x3) == 0x3;
15940 bool IsHighZero = (Zeroable & 0xc) == 0xc;
15941
15942 // Try to use an insert into a zero vector.
15943 if (WidenedMask[0] == 0 && IsHighZero) {
15944 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15945 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15946 DAG.getVectorIdxConstant(0, DL));
15947 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15948 getZeroVector(VT, Subtarget, DAG, DL), LoV,
15949 DAG.getVectorIdxConstant(0, DL));
15950 }
15951
15952 // TODO: If minimizing size and one of the inputs is a zero vector and the
15953 // the zero vector has only one use, we could use a VPERM2X128 to save the
15954 // instruction bytes needed to explicitly generate the zero vector.
15955
15956 // Blends are faster and handle all the non-lane-crossing cases.
15957 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15958 Subtarget, DAG))
15959 return Blend;
15960
15961 // If either input operand is a zero vector, use VPERM2X128 because its mask
15962 // allows us to replace the zero input with an implicit zero.
15963 if (!IsLowZero && !IsHighZero) {
15964 // Check for patterns which can be matched with a single insert of a 128-bit
15965 // subvector.
15966 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
15967 if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
15968
15969 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15970 // this will likely become vinsertf128 which can't fold a 256-bit memop.
15972 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15973 SDValue SubVec =
15974 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
15975 DAG.getVectorIdxConstant(0, DL));
15976 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15977 DAG.getVectorIdxConstant(2, DL));
15978 }
15979 }
15980
15981 // Try to use SHUF128 if possible.
15982 if (Subtarget.hasVLX()) {
15983 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15984 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15985 ((WidenedMask[1] % 2) << 1);
15986 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
15987 DAG.getTargetConstant(PermMask, DL, MVT::i8));
15988 }
15989 }
15990 }
15991
15992 // Otherwise form a 128-bit permutation. After accounting for undefs,
15993 // convert the 64-bit shuffle mask selection values into 128-bit
15994 // selection bits by dividing the indexes by 2 and shifting into positions
15995 // defined by a vperm2*128 instruction's immediate control byte.
15996
15997 // The immediate permute control byte looks like this:
15998 // [1:0] - select 128 bits from sources for low half of destination
15999 // [2] - ignore
16000 // [3] - zero low half of destination
16001 // [5:4] - select 128 bits from sources for high half of destination
16002 // [6] - ignore
16003 // [7] - zero high half of destination
16004
16005 assert((WidenedMask[0] >= 0 || IsLowZero) &&
16006 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
16007
16008 unsigned PermMask = 0;
16009 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
16010 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
16011
16012 // Check the immediate mask and replace unused sources with undef.
16013 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
16014 V1 = DAG.getUNDEF(VT);
16015 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
16016 V2 = DAG.getUNDEF(VT);
16017
16018 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16019 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16020}
16021
16022/// Lower a vector shuffle by first fixing the 128-bit lanes and then
16023/// shuffling each lane.
16024///
16025/// This attempts to create a repeated lane shuffle where each lane uses one
16026/// or two of the lanes of the inputs. The lanes of the input vectors are
16027/// shuffled in one or two independent shuffles to get the lanes into the
16028/// position needed by the final shuffle.
16030 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16031 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16032 // This is only useful for binary shuffle with a non-repeating mask.
16033 if (V2.isUndef() || is128BitLaneRepeatedShuffleMask(VT, Mask))
16034 return SDValue();
16035
16036 int NumElts = Mask.size();
16037 int NumLanes = VT.getSizeInBits() / 128;
16038 int NumLaneElts = 128 / VT.getScalarSizeInBits();
16039 SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16040 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16041
16042 // First pass will try to fill in the RepeatMask from lanes that need two
16043 // sources.
16044 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16045 int Srcs[2] = {-1, -1};
16046 SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16047 for (int i = 0; i != NumLaneElts; ++i) {
16048 int M = Mask[(Lane * NumLaneElts) + i];
16049 if (M < 0)
16050 continue;
16051 // Determine which of the possible input lanes (NumLanes from each source)
16052 // this element comes from. Assign that as one of the sources for this
16053 // lane. We can assign up to 2 sources for this lane. If we run out
16054 // sources we can't do anything.
16055 int LaneSrc = M / NumLaneElts;
16056 int Src;
16057 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16058 Src = 0;
16059 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16060 Src = 1;
16061 else
16062 return SDValue();
16063
16064 Srcs[Src] = LaneSrc;
16065 InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16066 }
16067
16068 // If this lane has two sources, see if it fits with the repeat mask so far.
16069 if (Srcs[1] < 0)
16070 continue;
16071
16072 LaneSrcs[Lane][0] = Srcs[0];
16073 LaneSrcs[Lane][1] = Srcs[1];
16074
16075 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16076 assert(M1.size() == M2.size() && "Unexpected mask size");
16077 for (int i = 0, e = M1.size(); i != e; ++i)
16078 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16079 return false;
16080 return true;
16081 };
16082
16083 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16084 assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
16085 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16086 int M = Mask[i];
16087 if (M < 0)
16088 continue;
16089 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
16090 "Unexpected mask element");
16091 MergedMask[i] = M;
16092 }
16093 };
16094
16095 if (MatchMasks(InLaneMask, RepeatMask)) {
16096 // Merge this lane mask into the final repeat mask.
16097 MergeMasks(InLaneMask, RepeatMask);
16098 continue;
16099 }
16100
16101 // Didn't find a match. Swap the operands and try again.
16102 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16104
16105 if (MatchMasks(InLaneMask, RepeatMask)) {
16106 // Merge this lane mask into the final repeat mask.
16107 MergeMasks(InLaneMask, RepeatMask);
16108 continue;
16109 }
16110
16111 // Couldn't find a match with the operands in either order.
16112 return SDValue();
16113 }
16114
16115 // Now handle any lanes with only one source.
16116 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16117 // If this lane has already been processed, skip it.
16118 if (LaneSrcs[Lane][0] >= 0)
16119 continue;
16120
16121 for (int i = 0; i != NumLaneElts; ++i) {
16122 int M = Mask[(Lane * NumLaneElts) + i];
16123 if (M < 0)
16124 continue;
16125
16126 // If RepeatMask isn't defined yet we can define it ourself.
16127 if (RepeatMask[i] < 0)
16128 RepeatMask[i] = M % NumLaneElts;
16129
16130 if (RepeatMask[i] < NumElts) {
16131 if (RepeatMask[i] != M % NumLaneElts)
16132 return SDValue();
16133 LaneSrcs[Lane][0] = M / NumLaneElts;
16134 } else {
16135 if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16136 return SDValue();
16137 LaneSrcs[Lane][1] = M / NumLaneElts;
16138 }
16139 }
16140
16141 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16142 return SDValue();
16143 }
16144
16145 SmallVector<int, 16> NewMask(NumElts, -1);
16146 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16147 int Src = LaneSrcs[Lane][0];
16148 for (int i = 0; i != NumLaneElts; ++i) {
16149 int M = -1;
16150 if (Src >= 0)
16151 M = Src * NumLaneElts + i;
16152 NewMask[Lane * NumLaneElts + i] = M;
16153 }
16154 }
16155 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16156 // Ensure we didn't get back the shuffle we started with.
16157 // FIXME: This is a hack to make up for some splat handling code in
16158 // getVectorShuffle.
16159 if (isa<ShuffleVectorSDNode>(NewV1) &&
16160 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16161 return SDValue();
16162
16163 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16164 int Src = LaneSrcs[Lane][1];
16165 for (int i = 0; i != NumLaneElts; ++i) {
16166 int M = -1;
16167 if (Src >= 0)
16168 M = Src * NumLaneElts + i;
16169 NewMask[Lane * NumLaneElts + i] = M;
16170 }
16171 }
16172 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16173 // Ensure we didn't get back the shuffle we started with.
16174 // FIXME: This is a hack to make up for some splat handling code in
16175 // getVectorShuffle.
16176 if (isa<ShuffleVectorSDNode>(NewV2) &&
16177 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16178 return SDValue();
16179
16180 for (int i = 0; i != NumElts; ++i) {
16181 if (Mask[i] < 0) {
16182 NewMask[i] = -1;
16183 continue;
16184 }
16185 NewMask[i] = RepeatMask[i % NumLaneElts];
16186 if (NewMask[i] < 0)
16187 continue;
16188
16189 NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16190 }
16191 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16192}
16193
16194/// If the input shuffle mask results in a vector that is undefined in all upper
16195/// or lower half elements and that mask accesses only 2 halves of the
16196/// shuffle's operands, return true. A mask of half the width with mask indexes
16197/// adjusted to access the extracted halves of the original shuffle operands is
16198/// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16199/// lower half of each input operand is accessed.
16200static bool
16202 int &HalfIdx1, int &HalfIdx2) {
16203 assert((Mask.size() == HalfMask.size() * 2) &&
16204 "Expected input mask to be twice as long as output");
16205
16206 // Exactly one half of the result must be undef to allow narrowing.
16207 bool UndefLower = isUndefLowerHalf(Mask);
16208 bool UndefUpper = isUndefUpperHalf(Mask);
16209 if (UndefLower == UndefUpper)
16210 return false;
16211
16212 unsigned HalfNumElts = HalfMask.size();
16213 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16214 HalfIdx1 = -1;
16215 HalfIdx2 = -1;
16216 for (unsigned i = 0; i != HalfNumElts; ++i) {
16217 int M = Mask[i + MaskIndexOffset];
16218 if (M < 0) {
16219 HalfMask[i] = M;
16220 continue;
16221 }
16222
16223 // Determine which of the 4 half vectors this element is from.
16224 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16225 int HalfIdx = M / HalfNumElts;
16226
16227 // Determine the element index into its half vector source.
16228 int HalfElt = M % HalfNumElts;
16229
16230 // We can shuffle with up to 2 half vectors, set the new 'half'
16231 // shuffle mask accordingly.
16232 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16233 HalfMask[i] = HalfElt;
16234 HalfIdx1 = HalfIdx;
16235 continue;
16236 }
16237 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16238 HalfMask[i] = HalfElt + HalfNumElts;
16239 HalfIdx2 = HalfIdx;
16240 continue;
16241 }
16242
16243 // Too many half vectors referenced.
16244 return false;
16245 }
16246
16247 return true;
16248}
16249
16250/// Given the output values from getHalfShuffleMask(), create a half width
16251/// shuffle of extracted vectors followed by an insert back to full width.
16253 ArrayRef<int> HalfMask, int HalfIdx1,
16254 int HalfIdx2, bool UndefLower,
16255 SelectionDAG &DAG, bool UseConcat = false) {
16256 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
16257 assert(V1.getValueType().isSimple() && "Expecting only simple types");
16258
16259 MVT VT = V1.getSimpleValueType();
16260 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16261 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16262
16263 auto getHalfVector = [&](int HalfIdx) {
16264 if (HalfIdx < 0)
16265 return DAG.getUNDEF(HalfVT);
16266 SDValue V = (HalfIdx < 2 ? V1 : V2);
16267 HalfIdx = (HalfIdx % 2) * HalfNumElts;
16268 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16269 DAG.getVectorIdxConstant(HalfIdx, DL));
16270 };
16271
16272 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16273 SDValue Half1 = getHalfVector(HalfIdx1);
16274 SDValue Half2 = getHalfVector(HalfIdx2);
16275 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16276 if (UseConcat) {
16277 SDValue Op0 = V;
16278 SDValue Op1 = DAG.getUNDEF(HalfVT);
16279 if (UndefLower)
16280 std::swap(Op0, Op1);
16281 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16282 }
16283
16284 unsigned Offset = UndefLower ? HalfNumElts : 0;
16285 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16287}
16288
16289/// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16290/// This allows for fast cases such as subvector extraction/insertion
16291/// or shuffling smaller vector types which can lower more efficiently.
16293 SDValue V2, ArrayRef<int> Mask,
16294 const X86Subtarget &Subtarget,
16295 SelectionDAG &DAG) {
16296 assert((VT.is256BitVector() || VT.is512BitVector()) &&
16297 "Expected 256-bit or 512-bit vector");
16298
16299 bool UndefLower = isUndefLowerHalf(Mask);
16300 if (!UndefLower && !isUndefUpperHalf(Mask))
16301 return SDValue();
16302
16303 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
16304 "Completely undef shuffle mask should have been simplified already");
16305
16306 // Upper half is undef and lower half is whole upper subvector.
16307 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16308 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16309 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16310 if (!UndefLower &&
16311 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16312 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16313 DAG.getVectorIdxConstant(HalfNumElts, DL));
16314 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16315 DAG.getVectorIdxConstant(0, DL));
16316 }
16317
16318 // Lower half is undef and upper half is whole lower subvector.
16319 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16320 if (UndefLower &&
16321 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16322 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16323 DAG.getVectorIdxConstant(0, DL));
16324 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16325 DAG.getVectorIdxConstant(HalfNumElts, DL));
16326 }
16327
16328 int HalfIdx1, HalfIdx2;
16329 SmallVector<int, 8> HalfMask(HalfNumElts);
16330 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
16331 return SDValue();
16332
16333 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
16334
16335 // Only shuffle the halves of the inputs when useful.
16336 unsigned NumLowerHalves =
16337 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
16338 unsigned NumUpperHalves =
16339 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
16340 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
16341
16342 // Determine the larger pattern of undef/halves, then decide if it's worth
16343 // splitting the shuffle based on subtarget capabilities and types.
16344 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
16345 if (!UndefLower) {
16346 // XXXXuuuu: no insert is needed.
16347 // Always extract lowers when setting lower - these are all free subreg ops.
16348 if (NumUpperHalves == 0)
16349 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16350 UndefLower, DAG);
16351
16352 if (NumUpperHalves == 1) {
16353 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
16354 if (Subtarget.hasAVX2()) {
16355 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
16356 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
16357 !is128BitUnpackShuffleMask(HalfMask, DAG) &&
16358 (!isSingleSHUFPSMask(HalfMask) ||
16359 Subtarget.hasFastVariableCrossLaneShuffle()))
16360 return SDValue();
16361 // If this is an unary shuffle (assume that the 2nd operand is
16362 // canonicalized to undef), then we can use vpermpd. Otherwise, we
16363 // are better off extracting the upper half of 1 operand and using a
16364 // narrow shuffle.
16365 if (EltWidth == 64 && V2.isUndef())
16366 return SDValue();
16367 // If this is an unary vXi8 shuffle with inplace halves, then perform as
16368 // full width pshufb, and then merge.
16369 if (EltWidth == 8 && HalfIdx1 == 0 && HalfIdx2 == 1)
16370 return SDValue();
16371 }
16372 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16373 if (Subtarget.hasAVX512() && VT.is512BitVector())
16374 return SDValue();
16375 // Extract + narrow shuffle is better than the wide alternative.
16376 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16377 UndefLower, DAG);
16378 }
16379
16380 // Don't extract both uppers, instead shuffle and then extract.
16381 assert(NumUpperHalves == 2 && "Half vector count went wrong");
16382 return SDValue();
16383 }
16384
16385 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
16386 if (NumUpperHalves == 0) {
16387 // AVX2 has efficient 64-bit element cross-lane shuffles.
16388 // TODO: Refine to account for unary shuffle, splat, and other masks?
16389 if (Subtarget.hasAVX2() && EltWidth == 64)
16390 return SDValue();
16391 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16392 if (Subtarget.hasAVX512() && VT.is512BitVector())
16393 return SDValue();
16394 // Narrow shuffle + insert is better than the wide alternative.
16395 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16396 UndefLower, DAG);
16397 }
16398
16399 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
16400 return SDValue();
16401}
16402
16403/// Handle case where shuffle sources are coming from the same 128-bit lane and
16404/// every lane can be represented as the same repeating mask - allowing us to
16405/// shuffle the sources with the repeating shuffle and then permute the result
16406/// to the destination lanes.
16408 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16409 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16410 int NumElts = VT.getVectorNumElements();
16411 int NumLanes = VT.getSizeInBits() / 128;
16412 int NumLaneElts = NumElts / NumLanes;
16413
16414 // On AVX2 we may be able to just shuffle the lowest elements and then
16415 // broadcast the result.
16416 if (Subtarget.hasAVX2()) {
16417 for (unsigned BroadcastSize : {16, 32, 64}) {
16418 if (BroadcastSize <= VT.getScalarSizeInBits())
16419 continue;
16420 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16421
16422 // Attempt to match a repeating pattern every NumBroadcastElts,
16423 // accounting for UNDEFs but only references the lowest 128-bit
16424 // lane of the inputs.
16425 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16426 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16427 for (int j = 0; j != NumBroadcastElts; ++j) {
16428 int M = Mask[i + j];
16429 if (M < 0)
16430 continue;
16431 int &R = RepeatMask[j];
16432 if (0 != ((M % NumElts) / NumLaneElts))
16433 return false;
16434 if (0 <= R && R != M)
16435 return false;
16436 R = M;
16437 }
16438 return true;
16439 };
16440
16441 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16442 if (!FindRepeatingBroadcastMask(RepeatMask))
16443 continue;
16444
16445 // Shuffle the (lowest) repeated elements in place for broadcast.
16446 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16447
16448 // Shuffle the actual broadcast.
16449 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16450 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16451 for (int j = 0; j != NumBroadcastElts; ++j)
16452 BroadcastMask[i + j] = j;
16453
16454 // Avoid returning the same shuffle operation. For example,
16455 // v8i32 = vector_shuffle<0,1,0,1,0,1,0,1> t5, undef:v8i32
16456 if (BroadcastMask == Mask)
16457 return SDValue();
16458
16459 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16460 BroadcastMask);
16461 }
16462 }
16463
16464 // Bail if the shuffle mask doesn't cross 128-bit lanes.
16465 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16466 return SDValue();
16467
16468 // Bail if we already have a repeated lane shuffle mask.
16469 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16470 return SDValue();
16471
16472 // Helper to look for repeated mask in each split sublane, and that those
16473 // sublanes can then be permuted into place.
16474 auto ShuffleSubLanes = [&](int SubLaneScale) {
16475 int NumSubLanes = NumLanes * SubLaneScale;
16476 int NumSubLaneElts = NumLaneElts / SubLaneScale;
16477
16478 // Check that all the sources are coming from the same lane and see if we
16479 // can form a repeating shuffle mask (local to each sub-lane). At the same
16480 // time, determine the source sub-lane for each destination sub-lane.
16481 int TopSrcSubLane = -1;
16482 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16483 SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
16484 SubLaneScale,
16485 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
16486
16487 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16488 // Extract the sub-lane mask, check that it all comes from the same lane
16489 // and normalize the mask entries to come from the first lane.
16490 int SrcLane = -1;
16491 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16492 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16493 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16494 if (M < 0)
16495 continue;
16496 int Lane = (M % NumElts) / NumLaneElts;
16497 if ((0 <= SrcLane) && (SrcLane != Lane))
16498 return SDValue();
16499 SrcLane = Lane;
16500 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16501 SubLaneMask[Elt] = LocalM;
16502 }
16503
16504 // Whole sub-lane is UNDEF.
16505 if (SrcLane < 0)
16506 continue;
16507
16508 // Attempt to match against the candidate repeated sub-lane masks.
16509 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16510 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16511 for (int i = 0; i != NumSubLaneElts; ++i) {
16512 if (M1[i] < 0 || M2[i] < 0)
16513 continue;
16514 if (M1[i] != M2[i])
16515 return false;
16516 }
16517 return true;
16518 };
16519
16520 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16521 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16522 continue;
16523
16524 // Merge the sub-lane mask into the matching repeated sub-lane mask.
16525 for (int i = 0; i != NumSubLaneElts; ++i) {
16526 int M = SubLaneMask[i];
16527 if (M < 0)
16528 continue;
16529 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
16530 "Unexpected mask element");
16531 RepeatedSubLaneMask[i] = M;
16532 }
16533
16534 // Track the top most source sub-lane - by setting the remaining to
16535 // UNDEF we can greatly simplify shuffle matching.
16536 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16537 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16538 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16539 break;
16540 }
16541
16542 // Bail if we failed to find a matching repeated sub-lane mask.
16543 if (Dst2SrcSubLanes[DstSubLane] < 0)
16544 return SDValue();
16545 }
16546 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
16547 "Unexpected source lane");
16548
16549 // Create a repeating shuffle mask for the entire vector.
16550 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16551 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16552 int Lane = SubLane / SubLaneScale;
16553 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16554 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16555 int M = RepeatedSubLaneMask[Elt];
16556 if (M < 0)
16557 continue;
16558 int Idx = (SubLane * NumSubLaneElts) + Elt;
16559 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16560 }
16561 }
16562
16563 // Shuffle each source sub-lane to its destination.
16564 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16565 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16566 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16567 if (SrcSubLane < 0)
16568 continue;
16569 for (int j = 0; j != NumSubLaneElts; ++j)
16570 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16571 }
16572
16573 // Avoid returning the same shuffle operation.
16574 // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
16575 if (RepeatedMask == Mask || SubLaneMask == Mask)
16576 return SDValue();
16577
16578 SDValue RepeatedShuffle =
16579 DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16580
16581 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16582 SubLaneMask);
16583 };
16584
16585 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16586 // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
16587 // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
16588 // Otherwise we can only permute whole 128-bit lanes.
16589 int MinSubLaneScale = 1, MaxSubLaneScale = 1;
16590 if (Subtarget.hasAVX2() && VT.is256BitVector()) {
16591 bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
16592 MinSubLaneScale = 2;
16593 MaxSubLaneScale =
16594 (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
16595 }
16596 if (Subtarget.hasBWI() && VT == MVT::v64i8)
16597 MinSubLaneScale = MaxSubLaneScale = 4;
16598
16599 for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
16600 if (SDValue Shuffle = ShuffleSubLanes(Scale))
16601 return Shuffle;
16602
16603 return SDValue();
16604}
16605
16607 bool &ForceV1Zero, bool &ForceV2Zero,
16608 unsigned &ShuffleImm, ArrayRef<int> Mask,
16609 const APInt &Zeroable) {
16610 int NumElts = VT.getVectorNumElements();
16611 assert(VT.getScalarSizeInBits() == 64 &&
16612 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
16613 "Unexpected data type for VSHUFPD");
16614 assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
16615 "Illegal shuffle mask");
16616
16617 bool ZeroLane[2] = { true, true };
16618 for (int i = 0; i < NumElts; ++i)
16619 ZeroLane[i & 1] &= Zeroable[i];
16620
16621 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
16622 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
16623 bool IsSHUFPD = true;
16624 bool IsCommutable = true;
16625 SmallVector<int, 8> SHUFPDMask(NumElts, -1);
16626 for (int i = 0; i < NumElts; ++i) {
16627 if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16628 continue;
16629 if (Mask[i] < 0)
16630 return false;
16631 int Val = (i & 6) + NumElts * (i & 1);
16632 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16633 if (Mask[i] < Val || Mask[i] > Val + 1)
16634 IsSHUFPD = false;
16635 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16636 IsCommutable = false;
16637 SHUFPDMask[i] = Mask[i] % 2;
16638 }
16639
16640 if (!IsSHUFPD && !IsCommutable)
16641 return false;
16642
16643 if (!IsSHUFPD && IsCommutable)
16644 std::swap(V1, V2);
16645
16646 ForceV1Zero = ZeroLane[0];
16647 ForceV2Zero = ZeroLane[1];
16648 ShuffleImm = getSHUFPDImm(SHUFPDMask);
16649 return true;
16650}
16651
16653 SDValue V2, ArrayRef<int> Mask,
16654 const APInt &Zeroable,
16655 const X86Subtarget &Subtarget,
16656 SelectionDAG &DAG) {
16657 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
16658 "Unexpected data type for VSHUFPD");
16659
16660 unsigned Immediate = 0;
16661 bool ForceV1Zero = false, ForceV2Zero = false;
16662 if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16663 Mask, Zeroable))
16664 return SDValue();
16665
16666 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16667 if (ForceV1Zero)
16668 V1 = getZeroVector(VT, Subtarget, DAG, DL);
16669 if (ForceV2Zero)
16670 V2 = getZeroVector(VT, Subtarget, DAG, DL);
16671
16672 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16673 DAG.getTargetConstant(Immediate, DL, MVT::i8));
16674}
16675
16676// Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16677// by zeroable elements in the remaining 24 elements. Turn this into two
16678// vmovqb instructions shuffled together.
16680 SDValue V1, SDValue V2,
16681 ArrayRef<int> Mask,
16682 const APInt &Zeroable,
16683 SelectionDAG &DAG) {
16684 assert(VT == MVT::v32i8 && "Unexpected type!");
16685
16686 // The first 8 indices should be every 8th element.
16687 if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16688 return SDValue();
16689
16690 // Remaining elements need to be zeroable.
16691 if (Zeroable.countl_one() < (Mask.size() - 8))
16692 return SDValue();
16693
16694 V1 = DAG.getBitcast(MVT::v4i64, V1);
16695 V2 = DAG.getBitcast(MVT::v4i64, V2);
16696
16697 V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16698 V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16699
16700 // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16701 // the upper bits of the result using an unpckldq.
16702 SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16703 { 0, 1, 2, 3, 16, 17, 18, 19,
16704 4, 5, 6, 7, 20, 21, 22, 23 });
16705 // Insert the unpckldq into a zero vector to widen to v32i8.
16706 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16707 DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16708 DAG.getVectorIdxConstant(0, DL));
16709}
16710
16711// a = shuffle v1, v2, mask1 ; interleaving lower lanes of v1 and v2
16712// b = shuffle v1, v2, mask2 ; interleaving higher lanes of v1 and v2
16713// =>
16714// ul = unpckl v1, v2
16715// uh = unpckh v1, v2
16716// a = vperm ul, uh
16717// b = vperm ul, uh
16718//
16719// Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
16720// and permute. We cannot directly match v3 because it is split into two
16721// 256-bit vectors in earlier isel stages. Therefore, this function matches a
16722// pair of 256-bit shuffles and makes sure the masks are consecutive.
16723//
16724// Once unpck and permute nodes are created, the permute corresponding to this
16725// shuffle is returned, while the other permute replaces the other half of the
16726// shuffle in the selection dag.
16728 SDValue V1, SDValue V2,
16729 ArrayRef<int> Mask,
16730 SelectionDAG &DAG) {
16731 if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
16732 VT != MVT::v32i8)
16733 return SDValue();
16734 // <B0, B1, B0+1, B1+1, ..., >
16735 auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
16736 unsigned Begin1) {
16737 size_t Size = Mask.size();
16738 assert(Size % 2 == 0 && "Expected even mask size");
16739 for (unsigned I = 0; I < Size; I += 2) {
16740 if (Mask[I] != (int)(Begin0 + I / 2) ||
16741 Mask[I + 1] != (int)(Begin1 + I / 2))
16742 return false;
16743 }
16744 return true;
16745 };
16746 // Check which half is this shuffle node
16747 int NumElts = VT.getVectorNumElements();
16748 size_t FirstQtr = NumElts / 2;
16749 size_t ThirdQtr = NumElts + NumElts / 2;
16750 bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
16751 bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
16752 if (!IsFirstHalf && !IsSecondHalf)
16753 return SDValue();
16754
16755 // Find the intersection between shuffle users of V1 and V2.
16756 SmallVector<SDNode *, 2> Shuffles;
16757 for (SDNode *User : V1->users())
16758 if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
16759 User->getOperand(1) == V2)
16760 Shuffles.push_back(User);
16761 // Limit user size to two for now.
16762 if (Shuffles.size() != 2)
16763 return SDValue();
16764 // Find out which half of the 512-bit shuffles is each smaller shuffle
16765 auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
16766 auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
16767 SDNode *FirstHalf;
16768 SDNode *SecondHalf;
16769 if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
16770 IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
16771 FirstHalf = Shuffles[0];
16772 SecondHalf = Shuffles[1];
16773 } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
16774 IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
16775 FirstHalf = Shuffles[1];
16776 SecondHalf = Shuffles[0];
16777 } else {
16778 return SDValue();
16779 }
16780 // Lower into unpck and perm. Return the perm of this shuffle and replace
16781 // the other.
16782 SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
16783 SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
16784 SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16785 DAG.getTargetConstant(0x20, DL, MVT::i8));
16786 SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16787 DAG.getTargetConstant(0x31, DL, MVT::i8));
16788 if (IsFirstHalf) {
16789 DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
16790 return Perm1;
16791 }
16792 DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
16793 return Perm2;
16794}
16795
16796/// Handle lowering of 4-lane 64-bit floating point shuffles.
16797///
16798/// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16799/// isn't available.
16801 const APInt &Zeroable, SDValue V1, SDValue V2,
16802 const X86Subtarget &Subtarget,
16803 SelectionDAG &DAG) {
16804 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16805 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16806 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16807
16808 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16809 Subtarget, DAG))
16810 return V;
16811
16812 if (V2.isUndef()) {
16813 // Check for being able to broadcast a single element.
16814 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16815 Mask, Subtarget, DAG))
16816 return Broadcast;
16817
16818 // Use low duplicate instructions for masks that match their pattern.
16819 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16820 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16821
16822 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16823 // Non-half-crossing single input shuffles can be lowered with an
16824 // interleaved permutation.
16825 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16826 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16827 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16828 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16829 }
16830
16831 // With AVX2 we have direct support for this permutation.
16832 if (Subtarget.hasAVX2())
16833 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16834 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16835
16836 // Try to create an in-lane repeating shuffle mask and then shuffle the
16837 // results into the target lanes.
16839 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16840 return V;
16841
16842 // Try to permute the lanes and then use a per-lane permute.
16843 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16844 Mask, DAG, Subtarget))
16845 return V;
16846
16847 // Otherwise, fall back.
16848 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16849 DAG, Subtarget);
16850 }
16851
16852 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16853 Zeroable, Subtarget, DAG))
16854 return Blend;
16855
16856 // Use dedicated unpack instructions for masks that match their pattern.
16857 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, V1, V2, Mask, DAG))
16858 return V;
16859
16860 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16861 Zeroable, Subtarget, DAG))
16862 return Op;
16863
16864 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16865 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16866 bool V1IsSplat = isShuffleMaskInputBroadcastable(0, Mask);
16867 bool V2IsSplat = isShuffleMaskInputBroadcastable(1, Mask);
16868
16869 // If we have lane crossing shuffles AND they don't all come from the lower
16870 // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16871 // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16872 // canonicalize to a blend of splat which isn't necessary for this combine.
16873 if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16874 !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16875 (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16876 (V2.getOpcode() != ISD::BUILD_VECTOR) &&
16877 (!Subtarget.hasAVX2() ||
16878 !((V1IsInPlace || V1IsSplat) && (V2IsInPlace || V2IsSplat))))
16879 return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
16880
16881 // If we have one input in place, then we can permute the other input and
16882 // blend the result.
16883 if (V1IsInPlace || V2IsInPlace)
16884 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16885 Zeroable, Subtarget, DAG);
16886
16887 // Try to create an in-lane repeating shuffle mask and then shuffle the
16888 // results into the target lanes.
16890 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16891 return V;
16892
16893 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16894 // shuffle. However, if we have AVX2 and either inputs are already in place,
16895 // we will be able to shuffle even across lanes the other input in a single
16896 // instruction so skip this pattern.
16897 if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
16899 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16900 return V;
16901
16902 // If we have VLX support, we can use VEXPAND.
16903 if (Subtarget.hasVLX())
16904 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4f64, V1, V2, Mask,
16905 Zeroable, Subtarget, DAG))
16906 return V;
16907
16908 // If we have AVX2 then we always want to lower with a blend because an v4 we
16909 // can fully permute the elements.
16910 if (Subtarget.hasAVX2())
16911 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16912 Zeroable, Subtarget, DAG);
16913
16914 // Otherwise fall back on generic lowering.
16915 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16916 Subtarget, DAG);
16917}
16918
16919/// Handle lowering of 4-lane 64-bit integer shuffles.
16920///
16921/// This routine is only called when we have AVX2 and thus a reasonable
16922/// instruction set for v4i64 shuffling..
16924 const APInt &Zeroable, SDValue V1, SDValue V2,
16925 const X86Subtarget &Subtarget,
16926 SelectionDAG &DAG) {
16927 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16928 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16929 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16930 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16931
16932 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16933 Subtarget, DAG))
16934 return V;
16935
16936 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16937 Zeroable, Subtarget, DAG))
16938 return Blend;
16939
16940 // Check for being able to broadcast a single element.
16941 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16942 Subtarget, DAG))
16943 return Broadcast;
16944
16945 // Try to use shift instructions if fast.
16946 if (Subtarget.preferLowerShuffleAsShift())
16947 if (SDValue Shift =
16948 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16949 Subtarget, DAG, /*BitwiseOnly*/ true))
16950 return Shift;
16951
16952 if (V2.isUndef()) {
16953 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16954 // can use lower latency instructions that will operate on both lanes.
16955 SmallVector<int, 2> RepeatedMask;
16956 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16957 SmallVector<int, 4> PSHUFDMask;
16958 narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16959 return DAG.getBitcast(
16960 MVT::v4i64,
16961 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16962 DAG.getBitcast(MVT::v8i32, V1),
16963 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16964 }
16965
16966 // AVX2 provides a direct instruction for permuting a single input across
16967 // lanes.
16968 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16969 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16970 }
16971
16972 // Try to use shift instructions.
16973 if (SDValue Shift =
16974 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
16975 DAG, /*BitwiseOnly*/ false))
16976 return Shift;
16977
16978 // If we have VLX support, we can use VALIGN or VEXPAND.
16979 if (Subtarget.hasVLX()) {
16980 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16981 Zeroable, Subtarget, DAG))
16982 return Rotate;
16983
16984 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4i64, V1, V2, Mask,
16985 Zeroable, Subtarget, DAG))
16986 return V;
16987 }
16988
16989 // Try to use PALIGNR.
16990 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16991 Subtarget, DAG))
16992 return Rotate;
16993
16994 // Use dedicated unpack instructions for masks that match their pattern.
16995 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, V1, V2, Mask, DAG))
16996 return V;
16997
16998 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16999 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
17000
17001 // If we have one input in place, then we can permute the other input and
17002 // blend the result.
17003 if (V1IsInPlace || V2IsInPlace)
17004 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17005 Zeroable, Subtarget, DAG);
17006
17007 // Try to create an in-lane repeating shuffle mask and then shuffle the
17008 // results into the target lanes.
17010 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17011 return V;
17012
17013 // Try to lower to PERMQ(BLENDD(V1,V2)).
17014 if (SDValue V =
17015 lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
17016 return V;
17017
17018 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17019 // shuffle. However, if we have AVX2 and either inputs are already in place,
17020 // we will be able to shuffle even across lanes the other input in a single
17021 // instruction so skip this pattern.
17022 if (!V1IsInPlace && !V2IsInPlace)
17024 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17025 return Result;
17026
17027 // Otherwise fall back on generic blend lowering.
17028 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17029 Zeroable, Subtarget, DAG);
17030}
17031
17032/// Handle lowering of 8-lane 32-bit floating point shuffles.
17033///
17034/// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17035/// isn't available.
17037 const APInt &Zeroable, SDValue V1, SDValue V2,
17038 const X86Subtarget &Subtarget,
17039 SelectionDAG &DAG) {
17040 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17041 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17042 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17043
17044 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17045 Zeroable, Subtarget, DAG))
17046 return Blend;
17047
17048 // Check for being able to broadcast a single element.
17049 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17050 Subtarget, DAG))
17051 return Broadcast;
17052
17053 if (!Subtarget.hasAVX2()) {
17054 SmallVector<int> InLaneMask;
17055 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
17056
17057 if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
17058 if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
17059 /*SimpleOnly*/ true))
17060 return R;
17061 }
17062 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17063 Zeroable, Subtarget, DAG))
17064 return DAG.getBitcast(MVT::v8f32, ZExt);
17065
17066 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17067 // options to efficiently lower the shuffle.
17068 SmallVector<int, 4> RepeatedMask;
17069 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17070 assert(RepeatedMask.size() == 4 &&
17071 "Repeated masks must be half the mask width!");
17072
17073 // Use even/odd duplicate instructions for masks that match their pattern.
17074 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17075 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17076 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17077 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17078
17079 if (V2.isUndef())
17080 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17081 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17082
17083 // Use dedicated unpack instructions for masks that match their pattern.
17084 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, V1, V2, Mask, DAG))
17085 return V;
17086
17087 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
17088 // have already handled any direct blends.
17089 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
17090 }
17091
17092 // Try to create an in-lane repeating shuffle mask and then shuffle the
17093 // results into the target lanes.
17095 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17096 return V;
17097
17098 // If we have a single input shuffle with different shuffle patterns in the
17099 // two 128-bit lanes use the variable mask to VPERMILPS.
17100 if (V2.isUndef()) {
17101 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
17102 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17103 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
17104 }
17105 if (Subtarget.hasAVX2()) {
17106 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17107 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17108 }
17109 // Otherwise, fall back.
17110 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17111 DAG, Subtarget);
17112 }
17113
17114 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17115 // shuffle.
17117 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17118 return Result;
17119
17120 // If we have VLX support, we can use VEXPAND.
17121 if (Subtarget.hasVLX())
17122 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f32, V1, V2, Mask,
17123 Zeroable, Subtarget, DAG))
17124 return V;
17125
17126 // Try to match an interleave of two v8f32s and lower them as unpck and
17127 // permutes using ymms. This needs to go before we try to split the vectors.
17128 // Don't attempt on AVX1 if we're likely to split vectors anyway.
17129 if ((Subtarget.hasAVX2() ||
17132 !Subtarget.hasAVX512())
17133 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
17134 Mask, DAG))
17135 return V;
17136
17137 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17138 // since after split we get a more efficient code using vpunpcklwd and
17139 // vpunpckhwd instrs than vblend.
17140 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
17141 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17142 Subtarget, DAG);
17143
17144 // If we have AVX2 then we always want to lower with a blend because at v8 we
17145 // can fully permute the elements.
17146 if (Subtarget.hasAVX2())
17147 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17148 Zeroable, Subtarget, DAG);
17149
17150 // Otherwise fall back on generic lowering.
17151 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17152 Subtarget, DAG);
17153}
17154
17155/// Handle lowering of 8-lane 32-bit integer shuffles.
17156///
17157/// This routine is only called when we have AVX2 and thus a reasonable
17158/// instruction set for v8i32 shuffling..
17160 const APInt &Zeroable, SDValue V1, SDValue V2,
17161 const X86Subtarget &Subtarget,
17162 SelectionDAG &DAG) {
17163 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17164 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17165 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17166 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
17167
17168 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
17169
17170 // Whenever we can lower this as a zext, that instruction is strictly faster
17171 // than any alternative. It also allows us to fold memory operands into the
17172 // shuffle in many cases.
17173 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17174 Zeroable, Subtarget, DAG))
17175 return ZExt;
17176
17177 // Try to match an interleave of two v8i32s and lower them as unpck and
17178 // permutes using ymms. This needs to go before we try to split the vectors.
17179 if (!Subtarget.hasAVX512())
17180 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
17181 Mask, DAG))
17182 return V;
17183
17184 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17185 // since after split we get a more efficient code than vblend by using
17186 // vpunpcklwd and vpunpckhwd instrs.
17187 if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
17188 !Subtarget.hasAVX512())
17189 return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17190 Subtarget, DAG);
17191
17192 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17193 Zeroable, Subtarget, DAG))
17194 return Blend;
17195
17196 // Check for being able to broadcast a single element.
17197 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17198 Subtarget, DAG))
17199 return Broadcast;
17200
17201 // Try to use shift instructions if fast.
17202 if (Subtarget.preferLowerShuffleAsShift()) {
17203 if (SDValue Shift =
17204 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17205 Subtarget, DAG, /*BitwiseOnly*/ true))
17206 return Shift;
17207 if (NumV2Elements == 0)
17208 if (SDValue Rotate =
17209 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17210 return Rotate;
17211 }
17212
17213 // If the shuffle mask is repeated in each 128-bit lane we can use more
17214 // efficient instructions that mirror the shuffles across the two 128-bit
17215 // lanes.
17216 SmallVector<int, 4> RepeatedMask;
17217 bool Is128BitLaneRepeatedShuffle =
17218 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17219 if (Is128BitLaneRepeatedShuffle) {
17220 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17221 if (V2.isUndef())
17222 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17223 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17224
17225 // Use dedicated unpack instructions for masks that match their pattern.
17226 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, V1, V2, Mask, DAG))
17227 return V;
17228 }
17229
17230 // Try to use shift instructions.
17231 if (SDValue Shift =
17232 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
17233 DAG, /*BitwiseOnly*/ false))
17234 return Shift;
17235
17236 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
17237 if (SDValue Rotate =
17238 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17239 return Rotate;
17240
17241 // If we have VLX support, we can use VALIGN or EXPAND.
17242 if (Subtarget.hasVLX()) {
17243 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17244 Zeroable, Subtarget, DAG))
17245 return Rotate;
17246
17247 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i32, V1, V2, Mask,
17248 Zeroable, Subtarget, DAG))
17249 return V;
17250 }
17251
17252 // Try to use byte rotation instructions.
17253 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17254 Subtarget, DAG))
17255 return Rotate;
17256
17257 // Try to create an in-lane repeating shuffle mask and then shuffle the
17258 // results into the target lanes.
17260 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17261 return V;
17262
17263 if (V2.isUndef()) {
17264 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17265 // because that should be faster than the variable permute alternatives.
17266 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, V1, V2, Mask, DAG))
17267 return V;
17268
17269 // If the shuffle patterns aren't repeated but it's a single input, directly
17270 // generate a cross-lane VPERMD instruction.
17271 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17272 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17273 }
17274
17275 // Assume that a single SHUFPS is faster than an alternative sequence of
17276 // multiple instructions (even if the CPU has a domain penalty).
17277 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17278 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17279 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17280 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17281 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17282 CastV1, CastV2, DAG);
17283 return DAG.getBitcast(MVT::v8i32, ShufPS);
17284 }
17285
17286 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17287 // shuffle.
17289 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17290 return Result;
17291
17292 // Otherwise fall back on generic blend lowering.
17293 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17294 Zeroable, Subtarget, DAG);
17295}
17296
17297/// Handle lowering of 16-lane 16-bit integer shuffles.
17298///
17299/// This routine is only called when we have AVX2 and thus a reasonable
17300/// instruction set for v16i16 shuffling..
17302 const APInt &Zeroable, SDValue V1, SDValue V2,
17303 const X86Subtarget &Subtarget,
17304 SelectionDAG &DAG) {
17305 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17306 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17307 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17308 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
17309
17310 // Whenever we can lower this as a zext, that instruction is strictly faster
17311 // than any alternative. It also allows us to fold memory operands into the
17312 // shuffle in many cases.
17314 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17315 return ZExt;
17316
17317 // Check for being able to broadcast a single element.
17318 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17319 Subtarget, DAG))
17320 return Broadcast;
17321
17322 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17323 Zeroable, Subtarget, DAG))
17324 return Blend;
17325
17326 // Use dedicated unpack instructions for masks that match their pattern.
17327 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, V1, V2, Mask, DAG))
17328 return V;
17329
17330 // Use dedicated pack instructions for masks that match their pattern.
17331 if (SDValue V =
17332 lowerShuffleWithPACK(DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17333 return V;
17334
17335 // Try to use lower using a truncation.
17336 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17337 Subtarget, DAG))
17338 return V;
17339
17340 // Try to use shift instructions.
17341 if (SDValue Shift =
17342 lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17343 Subtarget, DAG, /*BitwiseOnly*/ false))
17344 return Shift;
17345
17346 // Try to use byte rotation instructions.
17347 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17348 Subtarget, DAG))
17349 return Rotate;
17350
17351 // Try to create an in-lane repeating shuffle mask and then shuffle the
17352 // results into the target lanes.
17354 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17355 return V;
17356
17357 if (V2.isUndef()) {
17358 // Try to use bit rotation instructions.
17359 if (SDValue Rotate =
17360 lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17361 return Rotate;
17362
17363 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17364 // because that should be faster than the variable permute alternatives.
17365 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, V1, V2, Mask, DAG))
17366 return V;
17367
17368 // There are no generalized cross-lane shuffle operations available on i16
17369 // element types.
17370 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17372 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17373 return V;
17374
17375 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17376 DAG, Subtarget);
17377 }
17378
17379 SmallVector<int, 8> RepeatedMask;
17380 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17381 // As this is a single-input shuffle, the repeated mask should be
17382 // a strictly valid v8i16 mask that we can pass through to the v8i16
17383 // lowering to handle even the v16 case.
17385 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17386 }
17387 }
17388
17389 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17390 Zeroable, Subtarget, DAG))
17391 return PSHUFB;
17392
17393 // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17394 if (Subtarget.hasBWI())
17395 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17396
17397 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17398 // shuffle.
17400 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17401 return Result;
17402
17403 // Try to permute the lanes and then use a per-lane permute.
17405 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17406 return V;
17407
17408 // Try to match an interleave of two v16i16s and lower them as unpck and
17409 // permutes using ymms.
17410 if (!Subtarget.hasAVX512())
17411 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
17412 Mask, DAG))
17413 return V;
17414
17415 // Otherwise fall back on generic lowering.
17416 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17417 Subtarget, DAG);
17418}
17419
17420/// Handle lowering of 32-lane 8-bit integer shuffles.
17421///
17422/// This routine is only called when we have AVX2 and thus a reasonable
17423/// instruction set for v32i8 shuffling..
17425 const APInt &Zeroable, SDValue V1, SDValue V2,
17426 const X86Subtarget &Subtarget,
17427 SelectionDAG &DAG) {
17428 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17429 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17430 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17431 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
17432
17433 // Whenever we can lower this as a zext, that instruction is strictly faster
17434 // than any alternative. It also allows us to fold memory operands into the
17435 // shuffle in many cases.
17436 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17437 Zeroable, Subtarget, DAG))
17438 return ZExt;
17439
17440 // Check for being able to broadcast a single element.
17441 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17442 Subtarget, DAG))
17443 return Broadcast;
17444
17445 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17446 Zeroable, Subtarget, DAG))
17447 return Blend;
17448
17449 // Use dedicated unpack instructions for masks that match their pattern.
17450 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, V1, V2, Mask, DAG))
17451 return V;
17452
17453 // Use dedicated pack instructions for masks that match their pattern.
17454 if (SDValue V =
17455 lowerShuffleWithPACK(DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17456 return V;
17457
17458 // Try to use lower using a truncation.
17459 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17460 Subtarget, DAG))
17461 return V;
17462
17463 // Try to use shift instructions.
17464 if (SDValue Shift =
17465 lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
17466 DAG, /*BitwiseOnly*/ false))
17467 return Shift;
17468
17469 // Try to use byte rotation instructions.
17470 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17471 Subtarget, DAG))
17472 return Rotate;
17473
17474 // Try to use bit rotation instructions.
17475 if (V2.isUndef())
17476 if (SDValue Rotate =
17477 lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17478 return Rotate;
17479
17480 // Try to create an in-lane repeating shuffle mask and then shuffle the
17481 // results into the target lanes.
17483 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17484 return V;
17485
17486 // There are no generalized cross-lane shuffle operations available on i8
17487 // element types.
17488 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17489 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17490 // because that should be faster than the variable permute alternatives.
17491 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, V1, V2, Mask, DAG))
17492 return V;
17493
17495 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17496 return V;
17497
17498 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17499 DAG, Subtarget);
17500 }
17501
17502 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17503 Zeroable, Subtarget, DAG))
17504 return PSHUFB;
17505
17506 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17507 if (Subtarget.hasVBMI())
17508 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17509
17510 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17511 // shuffle.
17513 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17514 return Result;
17515
17516 // Try to permute the lanes and then use a per-lane permute.
17518 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17519 return V;
17520
17521 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17522 // by zeroable elements in the remaining 24 elements. Turn this into two
17523 // vmovqb instructions shuffled together.
17524 if (Subtarget.hasVLX())
17525 if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
17526 Mask, Zeroable, DAG))
17527 return V;
17528
17529 // Try to match an interleave of two v32i8s and lower them as unpck and
17530 // permutes using ymms.
17531 if (!Subtarget.hasAVX512())
17532 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
17533 Mask, DAG))
17534 return V;
17535
17536 // Otherwise fall back on generic lowering.
17537 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17538 Subtarget, DAG);
17539}
17540
17541/// High-level routine to lower various 256-bit x86 vector shuffles.
17542///
17543/// This routine either breaks down the specific type of a 256-bit x86 vector
17544/// shuffle or splits it into two 128-bit shuffles and fuses the results back
17545/// together based on the available instructions.
17547 SDValue V1, SDValue V2, const APInt &Zeroable,
17548 const X86Subtarget &Subtarget,
17549 SelectionDAG &DAG) {
17550 // If we have a single input to the zero element, insert that into V1 if we
17551 // can do so cheaply.
17552 int NumElts = VT.getVectorNumElements();
17553 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17554
17555 if (NumV2Elements == 1 && Mask[0] >= NumElts)
17557 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17558 return Insertion;
17559
17560 // Handle special cases where the lower or upper half is UNDEF.
17561 if (SDValue V =
17562 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17563 return V;
17564
17565 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
17566 // can check for those subtargets here and avoid much of the subtarget
17567 // querying in the per-vector-type lowering routines. With AVX1 we have
17568 // essentially *zero* ability to manipulate a 256-bit vector with integer
17569 // types. Since we'll use floating point types there eventually, just
17570 // immediately cast everything to a float and operate entirely in that domain.
17571 if (VT.isInteger() && !Subtarget.hasAVX2()) {
17572 int ElementBits = VT.getScalarSizeInBits();
17573 if (ElementBits < 32) {
17574 // No floating point type available, if we can't use the bit operations
17575 // for masking/blending then decompose into 128-bit vectors.
17576 if (SDValue V =
17577 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
17578 return V;
17579 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17580 return V;
17581 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17582 }
17583
17584 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
17586 V1 = DAG.getBitcast(FpVT, V1);
17587 V2 = DAG.getBitcast(FpVT, V2);
17588 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
17589 }
17590
17591 if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
17592 V1 = DAG.getBitcast(MVT::v16i16, V1);
17593 V2 = DAG.getBitcast(MVT::v16i16, V2);
17594 return DAG.getBitcast(VT,
17595 DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
17596 }
17597
17598 switch (VT.SimpleTy) {
17599 case MVT::v4f64:
17600 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17601 case MVT::v4i64:
17602 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17603 case MVT::v8f32:
17604 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17605 case MVT::v8i32:
17606 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17607 case MVT::v16i16:
17608 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17609 case MVT::v32i8:
17610 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17611
17612 default:
17613 llvm_unreachable("Not a valid 256-bit x86 vector type!");
17614 }
17615}
17616
17617/// Try to lower a vector shuffle as a 128-bit shuffles.
17619 const APInt &Zeroable, SDValue V1, SDValue V2,
17620 const X86Subtarget &Subtarget,
17621 SelectionDAG &DAG) {
17622 assert(VT.getScalarSizeInBits() == 64 &&
17623 "Unexpected element type size for 128bit shuffle.");
17624
17625 // To handle 256 bit vector requires VLX and most probably
17626 // function lowerV2X128VectorShuffle() is better solution.
17627 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
17628
17629 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17630 SmallVector<int, 4> Widened128Mask;
17631 if (!canWidenShuffleElements(Mask, Widened128Mask))
17632 return SDValue();
17633 assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
17634
17635 // Try to use an insert into a zero vector.
17636 if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17637 (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17638 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17639 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17640 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17641 DAG.getVectorIdxConstant(0, DL));
17642 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17643 getZeroVector(VT, Subtarget, DAG, DL), LoV,
17644 DAG.getVectorIdxConstant(0, DL));
17645 }
17646
17647 // Check for patterns which can be matched with a single insert of a 256-bit
17648 // subvector.
17649 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
17650 if (OnlyUsesV1 ||
17651 isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
17652 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17653 SDValue SubVec =
17654 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17655 DAG.getVectorIdxConstant(0, DL));
17656 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17657 DAG.getVectorIdxConstant(4, DL));
17658 }
17659
17660 // See if this is an insertion of the lower 128-bits of V2 into V1.
17661 bool IsInsert = true;
17662 int V2Index = -1;
17663 for (int i = 0; i < 4; ++i) {
17664 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17665 if (Widened128Mask[i] < 0)
17666 continue;
17667
17668 // Make sure all V1 subvectors are in place.
17669 if (Widened128Mask[i] < 4) {
17670 if (Widened128Mask[i] != i) {
17671 IsInsert = false;
17672 break;
17673 }
17674 } else {
17675 // Make sure we only have a single V2 index and its the lowest 128-bits.
17676 if (V2Index >= 0 || Widened128Mask[i] != 4) {
17677 IsInsert = false;
17678 break;
17679 }
17680 V2Index = i;
17681 }
17682 }
17683 if (IsInsert && V2Index >= 0) {
17684 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17685 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17686 DAG.getVectorIdxConstant(0, DL));
17687 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17688 }
17689
17690 // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17691 // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17692 // possible we at least ensure the lanes stay sequential to help later
17693 // combines.
17694 SmallVector<int, 2> Widened256Mask;
17695 if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17696 Widened128Mask.clear();
17697 narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17698 }
17699
17700 // Try to lower to vshuf64x2/vshuf32x4.
17701 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17702 int PermMask[4] = {-1, -1, -1, -1};
17703 // Ensure elements came from the same Op.
17704 for (int i = 0; i < 4; ++i) {
17705 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17706 if (Widened128Mask[i] < 0)
17707 continue;
17708
17709 SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17710 unsigned OpIndex = i / 2;
17711 if (Ops[OpIndex].isUndef())
17712 Ops[OpIndex] = Op;
17713 else if (Ops[OpIndex] != Op)
17714 return SDValue();
17715
17716 PermMask[i] = Widened128Mask[i] % 4;
17717 }
17718
17719 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17720 getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
17721}
17722
17723/// Handle lowering of 8-lane 64-bit floating point shuffles.
17725 const APInt &Zeroable, SDValue V1, SDValue V2,
17726 const X86Subtarget &Subtarget,
17727 SelectionDAG &DAG) {
17728 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17729 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17730 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17731
17732 if (V2.isUndef()) {
17733 // Use low duplicate instructions for masks that match their pattern.
17734 if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
17735 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17736
17737 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17738 // Non-half-crossing single input shuffles can be lowered with an
17739 // interleaved permutation.
17740 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17741 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17742 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17743 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17744 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17745 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17746 }
17747
17748 SmallVector<int, 4> RepeatedMask;
17749 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17750 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17751 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17752 }
17753
17754 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17755 V2, Subtarget, DAG))
17756 return Shuf128;
17757
17758 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, V1, V2, Mask, DAG))
17759 return Unpck;
17760
17761 // Check if the blend happens to exactly fit that of SHUFPD.
17762 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17763 Zeroable, Subtarget, DAG))
17764 return Op;
17765
17766 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f64, V1, V2, Mask, Zeroable,
17767 Subtarget, DAG))
17768 return V;
17769
17770 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17771 Zeroable, Subtarget, DAG))
17772 return Blend;
17773
17774 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPD which
17775 // requires an extra register for the index vector; VALIGNQ uses an immediate.
17776 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8f64, V1, V2, Mask,
17777 Zeroable, Subtarget, DAG))
17778 return Rotate;
17779
17780 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17781}
17782
17783/// Handle lowering of 16-lane 32-bit floating point shuffles.
17785 const APInt &Zeroable, SDValue V1, SDValue V2,
17786 const X86Subtarget &Subtarget,
17787 SelectionDAG &DAG) {
17788 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17789 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17790 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17791
17792 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17793 // options to efficiently lower the shuffle.
17794 SmallVector<int, 4> RepeatedMask;
17795 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17796 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17797
17798 // Use even/odd duplicate instructions for masks that match their pattern.
17799 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17800 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17801 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17802 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17803
17804 if (V2.isUndef())
17805 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17806 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17807
17808 // Use dedicated unpack instructions for masks that match their pattern.
17809 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, V1, V2, Mask, DAG))
17810 return V;
17811
17812 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17813 Zeroable, Subtarget, DAG))
17814 return Blend;
17815
17816 // Otherwise, fall back to a SHUFPS sequence.
17817 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17818 }
17819
17820 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17821 Zeroable, Subtarget, DAG))
17822 return Blend;
17823
17825 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17826 return DAG.getBitcast(MVT::v16f32, ZExt);
17827
17828 // Try to create an in-lane repeating shuffle mask and then shuffle the
17829 // results into the target lanes.
17831 DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17832 return V;
17833
17834 // If we have a single input shuffle with different shuffle patterns in the
17835 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17836 if (V2.isUndef() &&
17837 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17838 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17839 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17840 }
17841
17842 // If we have AVX512F support, we can use VEXPAND.
17843 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16f32, V1, V2, Mask,
17844 Zeroable, Subtarget, DAG))
17845 return V;
17846
17847 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPS which
17848 // requires an extra register for the index vector; VALIGND uses an immediate.
17849 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16f32, V1, V2, Mask,
17850 Zeroable, Subtarget, DAG))
17851 return Rotate;
17852
17853 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17854}
17855
17856/// Handle lowering of 8-lane 64-bit integer shuffles.
17858 const APInt &Zeroable, SDValue V1, SDValue V2,
17859 const X86Subtarget &Subtarget,
17860 SelectionDAG &DAG) {
17861 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17862 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17863 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17864
17865 // Try to use shift instructions if fast.
17866 if (Subtarget.preferLowerShuffleAsShift())
17867 if (SDValue Shift =
17868 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17869 Subtarget, DAG, /*BitwiseOnly*/ true))
17870 return Shift;
17871
17872 if (V2.isUndef()) {
17873 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17874 // can use lower latency instructions that will operate on all four
17875 // 128-bit lanes.
17876 SmallVector<int, 2> Repeated128Mask;
17877 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17878 SmallVector<int, 4> PSHUFDMask;
17879 narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17880 return DAG.getBitcast(
17881 MVT::v8i64,
17882 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17883 DAG.getBitcast(MVT::v16i32, V1),
17884 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17885 }
17886
17887 SmallVector<int, 4> Repeated256Mask;
17888 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17889 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17890 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17891 }
17892
17893 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17894 V2, Subtarget, DAG))
17895 return Shuf128;
17896
17897 // Try to use shift instructions.
17898 if (SDValue Shift =
17899 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
17900 DAG, /*BitwiseOnly*/ false))
17901 return Shift;
17902
17903 // Try to use VALIGN.
17904 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17905 Zeroable, Subtarget, DAG))
17906 return Rotate;
17907
17908 // Try to use PALIGNR.
17909 if (Subtarget.hasBWI())
17910 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17911 Subtarget, DAG))
17912 return Rotate;
17913
17914 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, V1, V2, Mask, DAG))
17915 return Unpck;
17916
17917 // If we have AVX512F support, we can use VEXPAND.
17918 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17919 Subtarget, DAG))
17920 return V;
17921
17922 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17923 Zeroable, Subtarget, DAG))
17924 return Blend;
17925
17926 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17927}
17928
17929/// Handle lowering of 16-lane 32-bit integer shuffles.
17931 const APInt &Zeroable, SDValue V1, SDValue V2,
17932 const X86Subtarget &Subtarget,
17933 SelectionDAG &DAG) {
17934 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17935 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17936 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17937
17938 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
17939
17940 // Whenever we can lower this as a zext, that instruction is strictly faster
17941 // than any alternative. It also allows us to fold memory operands into the
17942 // shuffle in many cases.
17944 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17945 return ZExt;
17946
17947 // Try to use shift instructions if fast.
17948 if (Subtarget.preferLowerShuffleAsShift()) {
17949 if (SDValue Shift =
17950 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17951 Subtarget, DAG, /*BitwiseOnly*/ true))
17952 return Shift;
17953 if (NumV2Elements == 0)
17954 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
17955 Subtarget, DAG))
17956 return Rotate;
17957 }
17958
17959 // If the shuffle mask is repeated in each 128-bit lane we can use more
17960 // efficient instructions that mirror the shuffles across the four 128-bit
17961 // lanes.
17962 SmallVector<int, 4> RepeatedMask;
17963 bool Is128BitLaneRepeatedShuffle =
17964 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17965 if (Is128BitLaneRepeatedShuffle) {
17966 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17967 if (V2.isUndef())
17968 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17969 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17970
17971 // Use dedicated unpack instructions for masks that match their pattern.
17972 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, V1, V2, Mask, DAG))
17973 return V;
17974 }
17975
17976 // Try to use shift instructions.
17977 if (SDValue Shift =
17978 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17979 Subtarget, DAG, /*BitwiseOnly*/ false))
17980 return Shift;
17981
17982 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
17983 if (SDValue Rotate =
17984 lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
17985 return Rotate;
17986
17987 // Try to use VALIGN.
17988 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17989 Zeroable, Subtarget, DAG))
17990 return Rotate;
17991
17992 // Try to use byte rotation instructions.
17993 if (Subtarget.hasBWI())
17994 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17995 Subtarget, DAG))
17996 return Rotate;
17997
17998 // Assume that a single SHUFPS is faster than using a permv shuffle.
17999 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
18000 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
18001 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
18002 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
18003 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
18004 CastV1, CastV2, DAG);
18005 return DAG.getBitcast(MVT::v16i32, ShufPS);
18006 }
18007
18008 // Try to create an in-lane repeating shuffle mask and then shuffle the
18009 // results into the target lanes.
18011 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
18012 return V;
18013
18014 // If we have AVX512F support, we can use VEXPAND.
18015 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16i32, V1, V2, Mask,
18016 Zeroable, Subtarget, DAG))
18017 return V;
18018
18019 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
18020 Zeroable, Subtarget, DAG))
18021 return Blend;
18022
18023 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
18024}
18025
18026/// Handle lowering of 32-lane 16-bit integer shuffles.
18028 const APInt &Zeroable, SDValue V1, SDValue V2,
18029 const X86Subtarget &Subtarget,
18030 SelectionDAG &DAG) {
18031 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18032 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18033 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18034 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
18035
18036 // Whenever we can lower this as a zext, that instruction is strictly faster
18037 // than any alternative. It also allows us to fold memory operands into the
18038 // shuffle in many cases.
18040 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18041 return ZExt;
18042
18043 // Use dedicated unpack instructions for masks that match their pattern.
18044 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, V1, V2, Mask, DAG))
18045 return V;
18046
18047 // Use dedicated pack instructions for masks that match their pattern.
18048 if (SDValue V =
18049 lowerShuffleWithPACK(DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18050 return V;
18051
18052 // Try to use shift instructions.
18053 if (SDValue Shift =
18054 lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
18055 Subtarget, DAG, /*BitwiseOnly*/ false))
18056 return Shift;
18057
18058 // Try to use byte rotation instructions.
18059 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
18060 Subtarget, DAG))
18061 return Rotate;
18062
18063 if (V2.isUndef()) {
18064 // Try to use bit rotation instructions.
18065 if (SDValue Rotate =
18066 lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
18067 return Rotate;
18068
18069 SmallVector<int, 8> RepeatedMask;
18070 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
18071 // As this is a single-input shuffle, the repeated mask should be
18072 // a strictly valid v8i16 mask that we can pass through to the v8i16
18073 // lowering to handle even the v32 case.
18074 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
18075 RepeatedMask, Subtarget, DAG);
18076 }
18077 }
18078
18079 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
18080 Zeroable, Subtarget, DAG))
18081 return Blend;
18082
18083 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18084 Zeroable, Subtarget, DAG))
18085 return PSHUFB;
18086
18087 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18088 // shuffle.
18090 DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18091 return Result;
18092
18093 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18094}
18095
18096/// Handle lowering of 64-lane 8-bit integer shuffles.
18098 const APInt &Zeroable, SDValue V1, SDValue V2,
18099 const X86Subtarget &Subtarget,
18100 SelectionDAG &DAG) {
18101 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18102 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18103 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
18104 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
18105
18106 // Whenever we can lower this as a zext, that instruction is strictly faster
18107 // than any alternative. It also allows us to fold memory operands into the
18108 // shuffle in many cases.
18110 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18111 return ZExt;
18112
18113 // Use dedicated unpack instructions for masks that match their pattern.
18114 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, V1, V2, Mask, DAG))
18115 return V;
18116
18117 // Use dedicated pack instructions for masks that match their pattern.
18118 if (SDValue V =
18119 lowerShuffleWithPACK(DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18120 return V;
18121
18122 // Try to use shift instructions.
18123 if (SDValue Shift =
18124 lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
18125 DAG, /*BitwiseOnly*/ false))
18126 return Shift;
18127
18128 // Try to use byte rotation instructions.
18129 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18130 Subtarget, DAG))
18131 return Rotate;
18132
18133 // Try to use bit rotation instructions.
18134 if (V2.isUndef())
18135 if (SDValue Rotate =
18136 lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18137 return Rotate;
18138
18139 // Lower as AND if possible.
18140 if (SDValue Masked =
18141 lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask, Zeroable, DAG))
18142 return Masked;
18143
18144 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18145 Zeroable, Subtarget, DAG))
18146 return PSHUFB;
18147
18148 // Try to create an in-lane repeating shuffle mask and then shuffle the
18149 // results into the target lanes.
18150 // FIXME: Avoid on VBMI targets as the post lane permute often interferes
18151 // with shuffle combining (should be fixed by topological DAG sorting).
18152 if (!Subtarget.hasVBMI())
18154 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18155 return V;
18156
18158 DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
18159 return Result;
18160
18161 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18162 Zeroable, Subtarget, DAG))
18163 return Blend;
18164
18165 if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
18166 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
18167 // PALIGNR will be cheaper than the second PSHUFB+OR.
18168 if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
18169 Mask, Subtarget, DAG))
18170 return V;
18171
18172 // VBMI can use VPERMV/VPERMV3 byte shuffles more efficiently than
18173 // OR(PSHUFB,PSHUFB).
18174 if (Subtarget.hasVBMI())
18175 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget,
18176 DAG);
18177
18178 // If we can't directly blend but can use PSHUFB, that will be better as it
18179 // can both shuffle and set up the inefficient blend.
18180 bool V1InUse, V2InUse;
18181 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
18182 DAG, V1InUse, V2InUse);
18183 }
18184
18185 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18186 // shuffle.
18188 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18189 return Result;
18190
18191 // VBMI can use VPERMV/VPERMV3 byte shuffles.
18192 if (Subtarget.hasVBMI())
18193 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18194
18195 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG,
18196 /*SimpleOnly*/ false);
18197}
18198
18199/// High-level routine to lower various 512-bit x86 vector shuffles.
18200///
18201/// This routine either breaks down the specific type of a 512-bit x86 vector
18202/// shuffle or splits it into two 256-bit shuffles and fuses the results back
18203/// together based on the available instructions.
18205 MVT VT, SDValue V1, SDValue V2,
18206 const APInt &Zeroable,
18207 const X86Subtarget &Subtarget,
18208 SelectionDAG &DAG) {
18209 assert(Subtarget.hasAVX512() &&
18210 "Cannot lower 512-bit vectors w/ basic ISA!");
18211
18212 // If we have a single input to the zero element, insert that into V1 if we
18213 // can do so cheaply.
18214 int NumElts = Mask.size();
18215 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18216
18217 if (NumV2Elements == 1 && Mask[0] >= NumElts)
18219 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18220 return Insertion;
18221
18222 // Handle special cases where the lower or upper half is UNDEF.
18223 if (SDValue V =
18224 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18225 return V;
18226
18227 // Check for being able to broadcast a single element.
18228 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
18229 Subtarget, DAG))
18230 return Broadcast;
18231
18232 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
18233 // Try using bit ops for masking and blending before falling back to
18234 // splitting.
18235 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
18236 return V;
18237 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18238 return V;
18239
18240 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
18241 }
18242
18243 if (VT == MVT::v32f16 || VT == MVT::v32bf16) {
18244 if (!Subtarget.hasBWI())
18245 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
18246 /*SimpleOnly*/ false);
18247
18248 V1 = DAG.getBitcast(MVT::v32i16, V1);
18249 V2 = DAG.getBitcast(MVT::v32i16, V2);
18250 return DAG.getBitcast(VT,
18251 DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
18252 }
18253
18254 // Dispatch to each element type for lowering. If we don't have support for
18255 // specific element type shuffles at 512 bits, immediately split them and
18256 // lower them. Each lowering routine of a given type is allowed to assume that
18257 // the requisite ISA extensions for that element type are available.
18258 switch (VT.SimpleTy) {
18259 case MVT::v8f64:
18260 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18261 case MVT::v16f32:
18262 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18263 case MVT::v8i64:
18264 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18265 case MVT::v16i32:
18266 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18267 case MVT::v32i16:
18268 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18269 case MVT::v64i8:
18270 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18271
18272 default:
18273 llvm_unreachable("Not a valid 512-bit x86 vector type!");
18274 }
18275}
18276
18278 MVT VT, SDValue V1, SDValue V2,
18279 const X86Subtarget &Subtarget,
18280 SelectionDAG &DAG) {
18281 // Shuffle should be unary.
18282 if (!V2.isUndef())
18283 return SDValue();
18284
18285 int ShiftAmt = -1;
18286 int NumElts = Mask.size();
18287 for (int i = 0; i != NumElts; ++i) {
18288 int M = Mask[i];
18289 assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
18290 "Unexpected mask index.");
18291 if (M < 0)
18292 continue;
18293
18294 // The first non-undef element determines our shift amount.
18295 if (ShiftAmt < 0) {
18296 ShiftAmt = M - i;
18297 // Need to be shifting right.
18298 if (ShiftAmt <= 0)
18299 return SDValue();
18300 }
18301 // All non-undef elements must shift by the same amount.
18302 if (ShiftAmt != M - i)
18303 return SDValue();
18304 }
18305 assert(ShiftAmt >= 0 && "All undef?");
18306
18307 // Great we found a shift right.
18308 SDValue Res = widenMaskVector(V1, false, Subtarget, DAG, DL);
18309 Res = DAG.getNode(X86ISD::KSHIFTR, DL, Res.getValueType(), Res,
18310 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18311 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18312 DAG.getVectorIdxConstant(0, DL));
18313}
18314
18315// Determine if this shuffle can be implemented with a KSHIFT instruction.
18316// Returns the shift amount if possible or -1 if not. This is a simplified
18317// version of matchShuffleAsShift.
18318static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18319 int MaskOffset, const APInt &Zeroable) {
18320 int Size = Mask.size();
18321
18322 auto CheckZeros = [&](int Shift, bool Left) {
18323 for (int j = 0; j < Shift; ++j)
18324 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18325 return false;
18326
18327 return true;
18328 };
18329
18330 auto MatchShift = [&](int Shift, bool Left) {
18331 unsigned Pos = Left ? Shift : 0;
18332 unsigned Low = Left ? 0 : Shift;
18333 unsigned Len = Size - Shift;
18334 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18335 };
18336
18337 for (int Shift = 1; Shift != Size; ++Shift)
18338 for (bool Left : {true, false})
18339 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18340 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18341 return Shift;
18342 }
18343
18344 return -1;
18345}
18346
18347
18348// Lower vXi1 vector shuffles.
18349// There is no a dedicated instruction on AVX-512 that shuffles the masks.
18350// The only way to shuffle bits is to sign-extend the mask vector to SIMD
18351// vector, shuffle and then truncate it back.
18353 MVT VT, SDValue V1, SDValue V2,
18354 const APInt &Zeroable,
18355 const X86Subtarget &Subtarget,
18356 SelectionDAG &DAG) {
18357 assert(Subtarget.hasAVX512() &&
18358 "Cannot lower 512-bit vectors w/o basic ISA!");
18359
18360 int NumElts = Mask.size();
18361 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18362
18363 // Try to recognize shuffles that are just padding a subvector with zeros.
18364 int SubvecElts = 0;
18365 int Src = -1;
18366 for (int i = 0; i != NumElts; ++i) {
18367 if (Mask[i] >= 0) {
18368 // Grab the source from the first valid mask. All subsequent elements need
18369 // to use this same source.
18370 if (Src < 0)
18371 Src = Mask[i] / NumElts;
18372 if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18373 break;
18374 }
18375
18376 ++SubvecElts;
18377 }
18378 assert(SubvecElts != NumElts && "Identity shuffle?");
18379
18380 // Clip to a power 2.
18381 SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
18382
18383 // Make sure the number of zeroable bits in the top at least covers the bits
18384 // not covered by the subvector.
18385 if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
18386 assert(Src >= 0 && "Expected a source!");
18387 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18388 SDValue Extract =
18389 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, Src == 0 ? V1 : V2,
18390 DAG.getVectorIdxConstant(0, DL));
18391 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18392 DAG.getConstant(0, DL, VT), Extract,
18393 DAG.getVectorIdxConstant(0, DL));
18394 }
18395
18396 // Try a simple shift right with undef elements. Later we'll try with zeros.
18397 if (SDValue Shift =
18398 lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget, DAG))
18399 return Shift;
18400
18401 // Try to match KSHIFTs.
18402 unsigned Offset = 0;
18403 for (SDValue V : {V1, V2}) {
18404 unsigned Opcode;
18405 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18406 if (ShiftAmt >= 0) {
18407 SDValue Res = widenMaskVector(V, false, Subtarget, DAG, DL);
18408 MVT WideVT = Res.getSimpleValueType();
18409 // Widened right shifts need two shifts to ensure we shift in zeroes.
18410 if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18411 int WideElts = WideVT.getVectorNumElements();
18412 // Shift left to put the original vector in the MSBs of the new size.
18413 Res =
18414 DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18415 DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18416 // Increase the shift amount to account for the left shift.
18417 ShiftAmt += WideElts - NumElts;
18418 }
18419
18420 Res = DAG.getNode(Opcode, DL, WideVT, Res,
18421 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18422 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18423 DAG.getVectorIdxConstant(0, DL));
18424 }
18425 Offset += NumElts; // Increment for next iteration.
18426 }
18427
18428 // If we're performing an unary shuffle on a SETCC result, try to shuffle the
18429 // ops instead.
18430 // TODO: What other unary shuffles would benefit from this?
18431 if (NumV2Elements == 0 && V1.getOpcode() == ISD::SETCC && V1->hasOneUse()) {
18432 SDValue Op0 = V1.getOperand(0);
18433 SDValue Op1 = V1.getOperand(1);
18434 ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
18435 EVT OpVT = Op0.getValueType();
18436 if (OpVT.getScalarSizeInBits() >= 32 || isBroadcastShuffleMask(Mask))
18437 return DAG.getSetCC(
18438 DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
18439 DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
18440 }
18441
18442 // If this is a sequential shuffle with zero'd elements - then lower to AND.
18443 bool IsBlendWithZero = all_of(enumerate(Mask), [&Zeroable](auto M) {
18444 return Zeroable[M.index()] || (M.value() == (int)M.index());
18445 });
18446 if (IsBlendWithZero) {
18447 const unsigned Width = std::max<unsigned>(NumElts, 8u);
18448 MVT IntVT = MVT::getIntegerVT(Width);
18449
18450 APInt MaskValue = (~Zeroable).zextOrTrunc(Width);
18451 SDValue MaskNode = DAG.getConstant(MaskValue, DL, IntVT);
18452
18453 MVT MaskVecVT = MVT::getVectorVT(MVT::i1, Width);
18454 SDValue MaskVecNode = DAG.getBitcast(MaskVecVT, MaskNode);
18455
18456 SDValue MaskVec = DAG.getExtractSubvector(DL, VT, MaskVecNode, 0);
18457 return DAG.getNode(ISD::AND, DL, VT, V1, MaskVec);
18458 }
18459
18460 MVT ExtVT;
18461 switch (VT.SimpleTy) {
18462 default:
18463 llvm_unreachable("Expected a vector of i1 elements");
18464 case MVT::v2i1:
18465 ExtVT = MVT::v2i64;
18466 break;
18467 case MVT::v4i1:
18468 ExtVT = MVT::v4i32;
18469 break;
18470 case MVT::v8i1:
18471 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18472 // shuffle.
18473 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18474 break;
18475 case MVT::v16i1:
18476 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18477 // 256-bit operation available.
18478 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18479 break;
18480 case MVT::v32i1:
18481 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18482 // 256-bit operation available.
18483 assert(Subtarget.hasBWI() && "Expected AVX512BW support");
18484 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18485 break;
18486 case MVT::v64i1:
18487 // Fall back to scalarization. FIXME: We can do better if the shuffle
18488 // can be partitioned cleanly.
18489 if (!Subtarget.useBWIRegs())
18490 return SDValue();
18491 ExtVT = MVT::v64i8;
18492 break;
18493 }
18494
18495 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18496 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18497
18498 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18499 // i1 was sign extended we can use X86ISD::CVT2MASK.
18500 int NumElems = VT.getVectorNumElements();
18501 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18502 (Subtarget.hasDQI() && (NumElems < 32)))
18503 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18504 Shuffle, ISD::SETGT);
18505
18506 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18507}
18508
18509/// Helper function that returns true if the shuffle mask should be
18510/// commuted to improve canonicalization.
18512 int NumElements = Mask.size();
18513
18514 int NumV1Elements = 0, NumV2Elements = 0;
18515 for (int M : Mask)
18516 if (M < 0)
18517 continue;
18518 else if (M < NumElements)
18519 ++NumV1Elements;
18520 else
18521 ++NumV2Elements;
18522
18523 // Commute the shuffle as needed such that more elements come from V1 than
18524 // V2. This allows us to match the shuffle pattern strictly on how many
18525 // elements come from V1 without handling the symmetric cases.
18526 if (NumV2Elements > NumV1Elements)
18527 return true;
18528
18529 assert(NumV1Elements > 0 && "No V1 indices");
18530
18531 if (NumV2Elements == 0)
18532 return false;
18533
18534 // When the number of V1 and V2 elements are the same, try to minimize the
18535 // number of uses of V2 in the low half of the vector. When that is tied,
18536 // ensure that the sum of indices for V1 is equal to or lower than the sum
18537 // indices for V2. When those are equal, try to ensure that the number of odd
18538 // indices for V1 is lower than the number of odd indices for V2.
18539 if (NumV1Elements == NumV2Elements) {
18540 int LowV1Elements = 0, LowV2Elements = 0;
18541 for (int M : Mask.slice(0, NumElements / 2))
18542 if (M >= NumElements)
18543 ++LowV2Elements;
18544 else if (M >= 0)
18545 ++LowV1Elements;
18546 if (LowV2Elements > LowV1Elements)
18547 return true;
18548 if (LowV2Elements == LowV1Elements) {
18549 int SumV1Indices = 0, SumV2Indices = 0;
18550 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18551 if (Mask[i] >= NumElements)
18552 SumV2Indices += i;
18553 else if (Mask[i] >= 0)
18554 SumV1Indices += i;
18555 if (SumV2Indices < SumV1Indices)
18556 return true;
18557 if (SumV2Indices == SumV1Indices) {
18558 int NumV1OddIndices = 0, NumV2OddIndices = 0;
18559 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18560 if (Mask[i] >= NumElements)
18561 NumV2OddIndices += i % 2;
18562 else if (Mask[i] >= 0)
18563 NumV1OddIndices += i % 2;
18564 if (NumV2OddIndices < NumV1OddIndices)
18565 return true;
18566 }
18567 }
18568 }
18569
18570 return false;
18571}
18572
18574 const X86Subtarget &Subtarget) {
18575 if (!Subtarget.hasAVX512())
18576 return false;
18577
18578 if (!V.getValueType().isSimple())
18579 return false;
18580
18581 MVT VT = V.getSimpleValueType().getScalarType();
18582 if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
18583 return false;
18584
18585 // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
18586 // are preferable to blendw/blendvb/masked-mov.
18587 if ((VT == MVT::i16 || VT == MVT::i8) &&
18588 V.getSimpleValueType().getSizeInBits() < 512)
18589 return false;
18590
18591 auto HasMaskOperation = [&](SDValue V) {
18592 // TODO: Currently we only check limited opcode. We probably extend
18593 // it to all binary operation by checking TLI.isBinOp().
18594 switch (V->getOpcode()) {
18595 default:
18596 return false;
18597 case ISD::ADD:
18598 case ISD::SUB:
18599 case ISD::AND:
18600 case ISD::XOR:
18601 case ISD::OR:
18602 case ISD::SMAX:
18603 case ISD::SMIN:
18604 case ISD::UMAX:
18605 case ISD::UMIN:
18606 case ISD::ABS:
18607 case ISD::SHL:
18608 case ISD::SRL:
18609 case ISD::SRA:
18610 case ISD::MUL:
18611 case ISD::PSEUDO_FMIN:
18612 case ISD::PSEUDO_FMAX:
18613 break;
18614 }
18615 if (!V->hasOneUse())
18616 return false;
18617
18618 return true;
18619 };
18620
18621 if (HasMaskOperation(V))
18622 return true;
18623
18624 return false;
18625}
18626
18627// Forward declaration.
18630 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
18631 const X86Subtarget &Subtarget);
18632
18633 /// Top-level lowering for x86 vector shuffles.
18634///
18635/// This handles decomposition, canonicalization, and lowering of all x86
18636/// vector shuffles. Most of the specific lowering strategies are encapsulated
18637/// above in helper routines. The canonicalization attempts to widen shuffles
18638/// to involve fewer lanes of wider elements, consolidate symmetric patterns
18639/// s.t. only one of the two inputs needs to be tested, etc.
18641 SelectionDAG &DAG) {
18643 ArrayRef<int> OrigMask = SVOp->getMask();
18644 SDValue V1 = Op.getOperand(0);
18645 SDValue V2 = Op.getOperand(1);
18646 MVT VT = Op.getSimpleValueType();
18647 int NumElements = VT.getVectorNumElements();
18648 SDLoc DL(Op);
18649 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18650
18651 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
18652 "Can't lower MMX shuffles");
18653
18654 bool V1IsUndef = V1.isUndef();
18655 bool V2IsUndef = V2.isUndef();
18656 if (V1IsUndef && V2IsUndef)
18657 return DAG.getUNDEF(VT);
18658
18659 // When we create a shuffle node we put the UNDEF node to second operand,
18660 // but in some cases the first operand may be transformed to UNDEF.
18661 // In this case we should just commute the node.
18662 if (V1IsUndef)
18663 return DAG.getCommutedVectorShuffle(*SVOp);
18664
18665 // Check for non-undef masks pointing at an undef vector and make the masks
18666 // undef as well. This makes it easier to match the shuffle based solely on
18667 // the mask.
18668 if (V2IsUndef &&
18669 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18670 SmallVector<int, 8> NewMask(OrigMask);
18671 for (int &M : NewMask)
18672 if (M >= NumElements)
18673 M = -1;
18674 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18675 }
18676
18677 // Check for illegal shuffle mask element index values.
18678 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18679 (void)MaskUpperLimit;
18680 assert(llvm::all_of(OrigMask,
18681 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
18682 "Out of bounds shuffle index");
18683
18684 // We actually see shuffles that are entirely re-arrangements of a set of
18685 // zero inputs. This mostly happens while decomposing complex shuffles into
18686 // simple ones. Directly lower these as a buildvector of zeros.
18687 APInt KnownUndef, KnownZero;
18688 computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
18689
18690 APInt Zeroable = KnownUndef | KnownZero;
18691 if (Zeroable.isAllOnes())
18692 return getZeroVector(VT, Subtarget, DAG, DL);
18693
18694 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
18695
18696 // Try to collapse shuffles into using a vector type with fewer elements but
18697 // wider element types. We cap this to not form integers or floating point
18698 // elements wider than 64 bits. It does not seem beneficial to form i128
18699 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
18700 SmallVector<int, 16> WidenedMask;
18701 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
18702 !canCombineAsMaskOperation(V1, Subtarget) &&
18703 !canCombineAsMaskOperation(V2, Subtarget) &&
18704 canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
18705 // Shuffle mask widening should not interfere with a broadcast opportunity
18706 // by obfuscating the operands with bitcasts.
18707 // TODO: Avoid lowering directly from this top-level function: make this
18708 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
18709 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
18710 Subtarget, DAG))
18711 return Broadcast;
18712
18713 MVT NewEltVT = VT.isFloatingPoint()
18716 int NewNumElts = NumElements / 2;
18717 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
18718 // Make sure that the new vector type is legal. For example, v2f64 isn't
18719 // legal on SSE1.
18720 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
18721 if (V2IsZero) {
18722 // Modify the new Mask to take all zeros from the all-zero vector.
18723 // Choose indices that are blend-friendly.
18724 bool UsedZeroVector = false;
18725 assert(is_contained(WidenedMask, SM_SentinelZero) &&
18726 "V2's non-undef elements are used?!");
18727 for (int i = 0; i != NewNumElts; ++i)
18728 if (WidenedMask[i] == SM_SentinelZero) {
18729 WidenedMask[i] = i + NewNumElts;
18730 UsedZeroVector = true;
18731 }
18732 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
18733 // some elements to be undef.
18734 if (UsedZeroVector)
18735 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
18736 }
18737 V1 = DAG.getBitcast(NewVT, V1);
18738 V2 = DAG.getBitcast(NewVT, V2);
18739 return DAG.getBitcast(
18740 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
18741 }
18742 }
18743
18744 SmallVector<SDValue> Ops = {V1, V2};
18745 SmallVector<int> Mask(OrigMask);
18746
18747 // Canonicalize the shuffle with any horizontal ops inputs.
18748 // Don't attempt this if the shuffle can still be widened as we may lose
18749 // whole lane shuffle patterns.
18750 // NOTE: This may update Ops and Mask.
18751 if (!canWidenShuffleElements(Mask)) {
18753 Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
18754 return DAG.getBitcast(VT, HOp);
18755
18756 V1 = DAG.getBitcast(VT, Ops[0]);
18757 V2 = DAG.getBitcast(VT, Ops[1]);
18758 assert(NumElements == (int)Mask.size() &&
18759 "canonicalizeShuffleMaskWithHorizOp "
18760 "shouldn't alter the shuffle mask size");
18761 }
18762
18763 // Canonicalize zeros/ones/fp splat constants to ensure no undefs.
18764 // These will be materialized uniformly anyway, so make splat matching easier.
18765 // TODO: Allow all int constants?
18766 auto CanonicalizeConstant = [VT, &DL, &DAG](SDValue V) {
18767 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
18768 BitVector Undefs;
18769 if (SDValue Splat = BV->getSplatValue(&Undefs)) {
18770 if (Undefs.any() &&
18773 V = DAG.getBitcast(VT, DAG.getSplat(BV->getValueType(0), DL, Splat));
18774 }
18775 }
18776 }
18777 return V;
18778 };
18779 V1 = CanonicalizeConstant(V1);
18780 V2 = CanonicalizeConstant(V2);
18781
18782 // Commute the shuffle if it will improve canonicalization.
18785 std::swap(V1, V2);
18786 }
18787
18788 // For each vector width, delegate to a specialized lowering routine.
18789 if (VT.is128BitVector())
18790 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18791
18792 if (VT.is256BitVector())
18793 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18794
18795 if (VT.is512BitVector())
18796 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18797
18798 if (Is1BitVector)
18799 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18800
18801 llvm_unreachable("Unimplemented!");
18802}
18803
18804// As legal vpcompress instructions depend on various AVX512 extensions, try to
18805// convert illegal vector sizes to legal ones to avoid expansion.
18807 SelectionDAG &DAG) {
18808 assert(Subtarget.hasAVX512() &&
18809 "Need AVX512 for custom VECTOR_COMPRESS lowering.");
18810
18811 SDLoc DL(Op);
18812 SDValue Vec = Op.getOperand(0);
18813 SDValue Mask = Op.getOperand(1);
18814 SDValue Passthru = Op.getOperand(2);
18815
18816 EVT VecVT = Vec.getValueType();
18817 EVT ElementVT = VecVT.getVectorElementType();
18818 unsigned NumElements = VecVT.getVectorNumElements();
18819 unsigned NumVecBits = VecVT.getFixedSizeInBits();
18820 unsigned NumElementBits = ElementVT.getFixedSizeInBits();
18821
18822 // 128- and 256-bit vectors with <= 16 elements can be converted to and
18823 // compressed as 512-bit vectors in AVX512F.
18824 if (NumVecBits != 128 && NumVecBits != 256)
18825 return SDValue();
18826
18827 if (NumElementBits == 32 || NumElementBits == 64) {
18828 unsigned NumLargeElements = 512 / NumElementBits;
18829 MVT LargeVecVT =
18830 MVT::getVectorVT(ElementVT.getSimpleVT(), NumLargeElements);
18831 MVT LargeMaskVT = MVT::getVectorVT(MVT::i1, NumLargeElements);
18832
18833 Vec = widenSubVector(LargeVecVT, Vec, /*ZeroNewElements=*/false, Subtarget,
18834 DAG, DL);
18835 Mask = widenSubVector(LargeMaskVT, Mask, /*ZeroNewElements=*/true,
18836 Subtarget, DAG, DL);
18837 Passthru = Passthru.isUndef() ? DAG.getUNDEF(LargeVecVT)
18838 : widenSubVector(LargeVecVT, Passthru,
18839 /*ZeroNewElements=*/false,
18840 Subtarget, DAG, DL);
18841
18842 SDValue Compressed =
18843 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18844 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VecVT, Compressed,
18845 DAG.getConstant(0, DL, MVT::i64));
18846 }
18847
18848 if (VecVT == MVT::v8i16 || VecVT == MVT::v8i8 || VecVT == MVT::v16i8 ||
18849 VecVT == MVT::v16i16) {
18850 MVT LageElementVT = MVT::getIntegerVT(512 / NumElements);
18851 EVT LargeVecVT = MVT::getVectorVT(LageElementVT, NumElements);
18852
18853 Vec = DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Vec);
18854 Passthru = Passthru.isUndef()
18855 ? DAG.getUNDEF(LargeVecVT)
18856 : DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Passthru);
18857
18858 SDValue Compressed =
18859 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18860 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Compressed);
18861 }
18862
18863 return SDValue();
18864}
18865
18866/// Try to lower a VSELECT instruction to a vector shuffle.
18868 const X86Subtarget &Subtarget,
18869 SelectionDAG &DAG) {
18870 SDValue Cond = Op.getOperand(0);
18871 SDValue LHS = Op.getOperand(1);
18872 SDValue RHS = Op.getOperand(2);
18873 MVT VT = Op.getSimpleValueType();
18874
18875 // Only non-legal VSELECTs reach this lowering, convert those into generic
18876 // shuffles and re-use the shuffle lowering path for blends.
18880 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18881 }
18882
18883 return SDValue();
18884}
18885
18886SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18887 SDValue Cond = Op.getOperand(0);
18888 SDValue LHS = Op.getOperand(1);
18889 SDValue RHS = Op.getOperand(2);
18890
18891 SDLoc dl(Op);
18892 MVT VT = Op.getSimpleValueType();
18893 if (isSoftF16(VT, Subtarget)) {
18894 MVT NVT = VT.changeVectorElementTypeToInteger();
18895 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
18896 DAG.getBitcast(NVT, LHS),
18897 DAG.getBitcast(NVT, RHS)));
18898 }
18899
18900 // A vselect where all conditions and data are constants can be optimized into
18901 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18905 return SDValue();
18906
18907 // Try to lower this to a blend-style vector shuffle. This can handle all
18908 // constant condition cases.
18909 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18910 return BlendOp;
18911
18912 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18913 // with patterns on the mask registers on AVX-512.
18914 MVT CondVT = Cond.getSimpleValueType();
18915 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18916 if (CondEltSize == 1)
18917 return Op;
18918
18919 // Variable blends are only legal from SSE4.1 onward.
18920 if (!Subtarget.hasSSE41())
18921 return SDValue();
18922
18923 unsigned EltSize = VT.getScalarSizeInBits();
18924 unsigned NumElts = VT.getVectorNumElements();
18925
18926 // Expand v32i16/v64i8 without BWI.
18927 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18928 return SDValue();
18929
18930 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18931 // into an i1 condition so that we can use the mask-based 512-bit blend
18932 // instructions.
18933 if (VT.getSizeInBits() == 512) {
18934 // Build a mask by testing the condition against zero.
18935 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18936 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18937 DAG.getConstant(0, dl, CondVT),
18938 ISD::SETNE);
18939 // Now return a new VSELECT using the mask.
18940 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18941 }
18942
18943 // SEXT/TRUNC cases where the mask doesn't match the destination size.
18944 if (CondEltSize != EltSize) {
18945 // If we don't have a sign splat, rely on the expansion.
18946 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18947 return SDValue();
18948
18949 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18950 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18951 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18952 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18953 }
18954
18955 // v16i16/v32i8 selects without AVX2, if the condition and another operand
18956 // are free to split, then better to split before expanding the
18957 // select. Don't bother with XOP as it has the fast VPCMOV instruction.
18958 // TODO: This is very similar to narrowVectorSelect.
18959 // TODO: Add Load splitting to isFreeToSplitVector ?
18960 if (EltSize < 32 && VT.is256BitVector() && !Subtarget.hasAVX2() &&
18961 !Subtarget.hasXOP()) {
18962 bool FreeCond = isFreeToSplitVector(Cond, DAG);
18963 bool FreeLHS = isFreeToSplitVector(LHS, DAG) ||
18964 (ISD::isNormalLoad(LHS.getNode()) && LHS.hasOneUse());
18965 bool FreeRHS = isFreeToSplitVector(RHS, DAG) ||
18966 (ISD::isNormalLoad(RHS.getNode()) && RHS.hasOneUse());
18967 if (FreeCond && (FreeLHS || FreeRHS))
18968 return splitVectorOp(Op, DAG, dl);
18969 }
18970
18971 // Only some types will be legal on some subtargets. If we can emit a legal
18972 // VSELECT-matching blend, return Op, and but if we need to expand, return
18973 // a null value.
18974 switch (VT.SimpleTy) {
18975 default:
18976 // Most of the vector types have blends past SSE4.1.
18977 return Op;
18978
18979 case MVT::v32i8:
18980 // The byte blends for AVX vectors were introduced only in AVX2.
18981 if (Subtarget.hasAVX2())
18982 return Op;
18983
18984 return SDValue();
18985
18986 case MVT::v8i16:
18987 case MVT::v16i16:
18988 case MVT::v8f16:
18989 case MVT::v16f16: {
18990 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18991 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18992 Cond = DAG.getBitcast(CastVT, Cond);
18993 LHS = DAG.getBitcast(CastVT, LHS);
18994 RHS = DAG.getBitcast(CastVT, RHS);
18995 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18996 return DAG.getBitcast(VT, Select);
18997 }
18998 }
18999}
19000
19002 MVT VT = Op.getSimpleValueType();
19003 SDValue Vec = Op.getOperand(0);
19004 SDValue Idx = Op.getOperand(1);
19005 assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
19006 SDLoc dl(Op);
19007
19009 return SDValue();
19010
19011 if (VT.getSizeInBits() == 8) {
19012 // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
19013 // we're going to zero extend the register or fold the store.
19016 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
19017 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19018 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19019
19020 unsigned IdxVal = Idx->getAsZExtVal();
19021 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
19022 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19023 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19024 }
19025
19026 if (VT == MVT::f32) {
19027 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
19028 // the result back to FR32 register. It's only worth matching if the
19029 // result has a single use which is a store or a bitcast to i32. And in
19030 // the case of a store, it's not worth it if the index is a constant 0,
19031 // because a MOVSSmr can be used instead, which is smaller and faster.
19032 if (!Op.hasOneUse())
19033 return SDValue();
19034 SDNode *User = *Op.getNode()->user_begin();
19035 if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
19036 (User->getOpcode() != ISD::BITCAST ||
19037 User->getValueType(0) != MVT::i32))
19038 return SDValue();
19039 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19040 DAG.getBitcast(MVT::v4i32, Vec), Idx);
19041 return DAG.getBitcast(MVT::f32, Extract);
19042 }
19043
19044 if (VT == MVT::i32 || VT == MVT::i64)
19045 return Op;
19046
19047 return SDValue();
19048}
19049
19050/// Extract one bit from mask vector, like v16i1 or v8i1.
19051/// AVX-512 feature.
19053 const X86Subtarget &Subtarget) {
19054 SDValue Vec = Op.getOperand(0);
19055 SDLoc dl(Vec);
19056 MVT VecVT = Vec.getSimpleValueType();
19057 SDValue Idx = Op.getOperand(1);
19058 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19059 MVT EltVT = Op.getSimpleValueType();
19060
19061 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
19062 "Unexpected vector type in ExtractBitFromMaskVector");
19063
19064 // variable index can't be handled in mask registers,
19065 // extend vector to VR512/128
19066 if (!IdxC) {
19067 unsigned NumElts = VecVT.getVectorNumElements();
19068 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
19069 // than extending to 128/256bit.
19070 if (NumElts == 1) {
19071 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19073 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, DAG.getBitcast(IntVT, Vec));
19074 }
19075 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19076 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19077 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
19078 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
19079 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
19080 }
19081
19082 unsigned IdxVal = IdxC->getZExtValue();
19083 if (IdxVal == 0) // the operation is legal
19084 return Op;
19085
19086 // Extend to natively supported kshift.
19087 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19088
19089 // Use kshiftr instruction to move to the lower element.
19090 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19091 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19092
19093 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19094 DAG.getVectorIdxConstant(0, dl));
19095}
19096
19097// Helper to find all the extracted elements from a vector.
19099 MVT VT = N->getSimpleValueType(0);
19100 unsigned NumElts = VT.getVectorNumElements();
19101 APInt DemandedElts = APInt::getZero(NumElts);
19102 for (SDNode *User : N->users()) {
19103 switch (User->getOpcode()) {
19104 case X86ISD::PEXTRB:
19105 case X86ISD::PEXTRW:
19108 DemandedElts.setAllBits();
19109 return DemandedElts;
19110 }
19111 DemandedElts.setBit(User->getConstantOperandVal(1));
19112 break;
19113 case ISD::BITCAST: {
19114 if (!User->getValueType(0).isSimple() ||
19115 !User->getValueType(0).isVector()) {
19116 DemandedElts.setAllBits();
19117 return DemandedElts;
19118 }
19119 APInt DemandedSrcElts = getExtractedDemandedElts(User);
19120 DemandedElts |= APIntOps::ScaleBitMask(DemandedSrcElts, NumElts);
19121 break;
19122 }
19123 default:
19124 DemandedElts.setAllBits();
19125 return DemandedElts;
19126 }
19127 }
19128 return DemandedElts;
19129}
19130
19131SDValue
19132X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
19133 SelectionDAG &DAG) const {
19134 SDLoc dl(Op);
19135 SDValue Vec = Op.getOperand(0);
19136 MVT VecVT = Vec.getSimpleValueType();
19137 SDValue Idx = Op.getOperand(1);
19138 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19139
19140 if (VecVT.getVectorElementType() == MVT::i1)
19141 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
19142
19143 if (!IdxC) {
19144 // Its more profitable to go through memory (1 cycles throughput)
19145 // than using VMOVD + VPERMV/PSHUFB sequence (2/3 cycles throughput)
19146 // IACA tool was used to get performance estimation
19147 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
19148 //
19149 // example : extractelement <16 x i8> %a, i32 %i
19150 //
19151 // Block Throughput: 3.00 Cycles
19152 // Throughput Bottleneck: Port5
19153 //
19154 // | Num Of | Ports pressure in cycles | |
19155 // | Uops | 0 - DV | 5 | 6 | 7 | |
19156 // ---------------------------------------------
19157 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
19158 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
19159 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
19160 // Total Num Of Uops: 4
19161 //
19162 //
19163 // Block Throughput: 1.00 Cycles
19164 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
19165 //
19166 // | | Ports pressure in cycles | |
19167 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
19168 // ---------------------------------------------------------
19169 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
19170 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
19171 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
19172 // Total Num Of Uops: 4
19173
19174 return SDValue();
19175 }
19176
19177 unsigned IdxVal = IdxC->getZExtValue();
19178
19179 // If this is a 256-bit vector result, first extract the 128-bit vector and
19180 // then extract the element from the 128-bit vector.
19181 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
19182 // Get the 128-bit vector.
19183 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
19184 MVT EltVT = VecVT.getVectorElementType();
19185
19186 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
19187 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
19188
19189 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
19190 // this can be done with a mask.
19191 IdxVal &= ElemsPerChunk - 1;
19192 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19193 DAG.getVectorIdxConstant(IdxVal, dl));
19194 }
19195
19196 assert(VecVT.is128BitVector() && "Unexpected vector length");
19197
19198 MVT VT = Op.getSimpleValueType();
19199
19200 if (VT == MVT::i16) {
19201 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
19202 // we're going to zero extend the register or fold the store (SSE41 only).
19203 if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
19204 !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
19205 if (Subtarget.hasFP16())
19206 return Op;
19207
19208 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
19209 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19210 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19211 }
19212
19213 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
19214 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19215 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19216 }
19217
19218 if (Subtarget.hasSSE41())
19219 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
19220 return Res;
19221
19222 // Only extract a single element from a v16i8 source - determine the common
19223 // DWORD/WORD that all extractions share, and extract the sub-byte.
19224 // TODO: Add QWORD MOVQ extraction?
19225 if (VT == MVT::i8) {
19226 APInt DemandedElts = getExtractedDemandedElts(Vec.getNode());
19227 assert(DemandedElts.getBitWidth() == 16 && "Vector width mismatch");
19228
19229 // Extract either the lowest i32 or any i16, and extract the sub-byte.
19230 int DWordIdx = IdxVal / 4;
19231 if (DWordIdx == 0 && DemandedElts == (DemandedElts & 15)) {
19232 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19233 DAG.getBitcast(MVT::v4i32, Vec),
19234 DAG.getVectorIdxConstant(DWordIdx, dl));
19235 int ShiftVal = (IdxVal % 4) * 8;
19236 if (ShiftVal != 0)
19237 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
19238 DAG.getConstant(ShiftVal, dl, MVT::i8));
19239 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19240 }
19241
19242 int WordIdx = IdxVal / 2;
19243 if (DemandedElts == (DemandedElts & (3 << (WordIdx * 2)))) {
19244 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
19245 DAG.getBitcast(MVT::v8i16, Vec),
19246 DAG.getVectorIdxConstant(WordIdx, dl));
19247 int ShiftVal = (IdxVal % 2) * 8;
19248 if (ShiftVal != 0)
19249 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
19250 DAG.getConstant(ShiftVal, dl, MVT::i8));
19251 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19252 }
19253 }
19254
19255 if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
19256 if (IdxVal == 0)
19257 return Op;
19258
19259 // Shuffle the element to the lowest element, then movss or movsh.
19260 SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
19261 Mask[0] = static_cast<int>(IdxVal);
19262 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19263 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19264 DAG.getVectorIdxConstant(0, dl));
19265 }
19266
19267 if (VT.getSizeInBits() == 64) {
19268 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
19269 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
19270 // to match extract_elt for f64.
19271 if (IdxVal == 0)
19272 return Op;
19273
19274 // UNPCKHPD the element to the lowest double word, then movsd.
19275 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
19276 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
19277 int Mask[2] = { 1, -1 };
19278 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19280 DAG.getVectorIdxConstant(0, dl));
19281 }
19282
19283 return SDValue();
19284}
19285
19286/// Insert one bit to mask vector, like v16i1 or v8i1.
19287/// AVX-512 feature.
19289 const X86Subtarget &Subtarget) {
19290 SDLoc dl(Op);
19291 SDValue Vec = Op.getOperand(0);
19292 SDValue Elt = Op.getOperand(1);
19293 SDValue Idx = Op.getOperand(2);
19294 MVT VecVT = Vec.getSimpleValueType();
19295
19296 if (!isa<ConstantSDNode>(Idx)) {
19297 // Non constant index. Extend source and destination,
19298 // insert element and then truncate the result.
19299 unsigned NumElts = VecVT.getVectorNumElements();
19300 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19301 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19302 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
19303 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
19304 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
19305 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
19306 }
19307
19308 // Copy into a k-register, extract to v1i1 and insert_subvector.
19309 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
19310 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
19311}
19312
19313SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
19314 SelectionDAG &DAG) const {
19315 MVT VT = Op.getSimpleValueType();
19316 MVT EltVT = VT.getVectorElementType();
19317 unsigned NumElts = VT.getVectorNumElements();
19318 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
19319
19320 if (EltVT == MVT::i1)
19321 return InsertBitToMaskVector(Op, DAG, Subtarget);
19322
19323 SDLoc dl(Op);
19324 SDValue N0 = Op.getOperand(0);
19325 SDValue N1 = Op.getOperand(1);
19326 SDValue N2 = Op.getOperand(2);
19327 auto *N2C = dyn_cast<ConstantSDNode>(N2);
19328
19329 if (!N2C) {
19330 // Variable insertion indices, usually we're better off spilling to stack,
19331 // but AVX512 can use a variable compare+select by comparing against all
19332 // possible vector indices, and FP insertion has less gpr->simd traffic.
19333 if (!(Subtarget.hasBWI() ||
19334 (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
19335 (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
19336 return SDValue();
19337
19338 MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
19339 MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
19340 if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
19341 return SDValue();
19342
19343 SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
19344 SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
19345 SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
19346
19347 SmallVector<SDValue, 16> RawIndices;
19348 for (unsigned I = 0; I != NumElts; ++I)
19349 RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
19350 SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
19351
19352 // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
19353 return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
19355 }
19356
19357 if (N2C->getAPIntValue().uge(NumElts))
19358 return SDValue();
19359 uint64_t IdxVal = N2C->getZExtValue();
19360
19361 bool IsZeroElt = X86::isZeroNode(N1);
19362 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
19363
19364 if (IsZeroElt || IsAllOnesElt) {
19365 // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
19366 // We don't deal with i8 0 since it appears to be handled elsewhere.
19367 if (IsAllOnesElt &&
19368 ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
19369 ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
19370 SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
19371 SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
19372 SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
19373 CstVectorElts[IdxVal] = OnesCst;
19374 SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
19375 return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
19376 }
19377 // See if we can do this more efficiently with a blend shuffle with a
19378 // rematerializable vector.
19379 if (Subtarget.hasSSE41() &&
19380 (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
19381 SmallVector<int, 8> BlendMask;
19382 for (unsigned i = 0; i != NumElts; ++i)
19383 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19384 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
19385 : getOnesVector(VT, DAG, dl);
19386 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
19387 }
19388 }
19389
19390 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
19391 // into that, and then insert the subvector back into the result.
19392 if (VT.is256BitVector() || VT.is512BitVector()) {
19393 // With a 256-bit vector, we can insert into the zero element efficiently
19394 // using a blend if we have AVX or AVX2 and the right data type.
19395 if (VT.is256BitVector() && IdxVal == 0) {
19396 // TODO: It is worthwhile to cast integer to floating point and back
19397 // and incur a domain crossing penalty if that's what we'll end up
19398 // doing anyway after extracting to a 128-bit vector.
19399 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19400 (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
19401 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19402 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19403 DAG.getTargetConstant(1, dl, MVT::i8));
19404 }
19405 }
19406
19407 unsigned NumEltsIn128 = 128 / EltSizeInBits;
19408 assert(isPowerOf2_32(NumEltsIn128) &&
19409 "Vectors will always have power-of-two number of elements.");
19410
19411 // If we are not inserting into the low 128-bit vector chunk,
19412 // then prefer the broadcast+blend sequence.
19413 // FIXME: relax the profitability check iff all N1 uses are insertions.
19414 if (IdxVal >= NumEltsIn128 &&
19415 ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
19416 (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
19417 X86::mayFoldLoad(N1, Subtarget)))) {
19418 SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
19419 SmallVector<int, 8> BlendMask;
19420 for (unsigned i = 0; i != NumElts; ++i)
19421 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19422 return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
19423 }
19424
19425 // Get the desired 128-bit vector chunk.
19426 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
19427
19428 // Insert the element into the desired chunk.
19429 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
19430 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
19431
19432 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
19433 DAG.getVectorIdxConstant(IdxIn128, dl));
19434
19435 // Insert the changed part back into the bigger vector
19436 return insert128BitVector(N0, V, IdxVal, DAG, dl);
19437 }
19438 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
19439
19440 // This will be just movw/movd/movq/movsh/movss/movsd.
19441 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
19442 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
19443 EltVT == MVT::f16 || EltVT == MVT::i64) {
19444 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19445 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19446 }
19447
19448 // We can't directly insert an i8 or i16 into a vector, so zero extend
19449 // it to i32 first.
19450 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
19451 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
19452 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
19453 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
19454 N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19455 return DAG.getBitcast(VT, N1);
19456 }
19457 }
19458
19459 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
19460 // argument. SSE41 required for pinsrb.
19461 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
19462 unsigned Opc;
19463 if (VT == MVT::v8i16) {
19464 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
19465 Opc = X86ISD::PINSRW;
19466 } else {
19467 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
19468 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
19469 Opc = X86ISD::PINSRB;
19470 }
19471
19472 assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
19473 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
19474 N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
19475 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
19476 }
19477
19478 if (Subtarget.hasSSE41()) {
19479 if (EltVT == MVT::f32) {
19480 // Bits [7:6] of the constant are the source select. This will always be
19481 // zero here. The DAG Combiner may combine an extract_elt index into
19482 // these bits. For example (insert (extract, 3), 2) could be matched by
19483 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
19484 // Bits [5:4] of the constant are the destination select. This is the
19485 // value of the incoming immediate.
19486 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
19487 // combine either bitwise AND or insert of float 0.0 to set these bits.
19488
19489 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
19490 if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
19491 // If this is an insertion of 32-bits into the low 32-bits of
19492 // a vector, we prefer to generate a blend with immediate rather
19493 // than an insertps. Blends are simpler operations in hardware and so
19494 // will always have equal or better performance than insertps.
19495 // But if optimizing for size and there's a load folding opportunity,
19496 // generate insertps because blendps does not have a 32-bit memory
19497 // operand form.
19498 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19499 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
19500 DAG.getTargetConstant(1, dl, MVT::i8));
19501 }
19502 // Create this as a scalar to vector..
19503 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19504 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
19505 DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
19506 }
19507
19508 // PINSR* works with constant index.
19509 if (EltVT == MVT::i32 || EltVT == MVT::i64)
19510 return Op;
19511 }
19512
19513 return SDValue();
19514}
19515
19516static SDValue LowerFLDEXP(SDValue Op, const X86Subtarget &Subtarget,
19517 SelectionDAG &DAG) {
19518 SDLoc DL(Op);
19519 SDValue X = Op.getOperand(0);
19520 MVT XTy = X.getSimpleValueType();
19521 SDValue Exp = Op.getOperand(1);
19522
19523 switch (XTy.SimpleTy) {
19524 default:
19525 return SDValue();
19526 case MVT::f16:
19527 if (!Subtarget.hasFP16())
19528 X = DAG.getFPExtendOrRound(X, DL, MVT::f32);
19529 [[fallthrough]];
19530 case MVT::f32:
19531 case MVT::f64: {
19532 MVT VT = MVT::getVectorVT(X.getSimpleValueType(),
19533 128 / X.getSimpleValueType().getSizeInBits());
19534 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, X.getValueType(), Exp);
19535 SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, X);
19536 SDValue VExp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Exp);
19537 SDValue Scalefs = DAG.getNode(X86ISD::SCALEFS, DL, VT, VX, VExp);
19538 SDValue Final = DAG.getExtractVectorElt(DL, X.getValueType(), Scalefs, 0);
19539 return DAG.getFPExtendOrRound(Final, DL, XTy);
19540 }
19541 case MVT::v4f32:
19542 case MVT::v2f64:
19543 case MVT::v8f32:
19544 case MVT::v4f64:
19545 case MVT::v16f32:
19546 case MVT::v8f64:
19547 if (XTy.getSizeInBits() == 512 || Subtarget.hasVLX()) {
19548 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19549 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19550 }
19551 break;
19552 case MVT::v8f16:
19553 case MVT::v16f16:
19554 if (Subtarget.hasFP16()) {
19555 if (Subtarget.hasVLX()) {
19556 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19557 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19558 }
19559 break;
19560 }
19561 X = DAG.getFPExtendOrRound(X, DL, XTy.changeVectorElementType(MVT::f32));
19562 Exp = DAG.getSExtOrTrunc(Exp, DL,
19563 X.getSimpleValueType().changeTypeToInteger());
19564 break;
19565 case MVT::v32f16:
19566 if (Subtarget.hasFP16()) {
19567 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19568 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19569 }
19570 return splitVectorOp(Op, DAG, DL);
19571 }
19572 SDValue WideX = widenSubVector(X, true, Subtarget, DAG, DL, 512);
19573 // Widen Exp to the same *lane count* as WideX (not necessarily 512 bits) so
19574 // SINT_TO_FP has matching vector lengths. For wide f64 the int exponent
19575 // vector is narrower than 512 bits (e.g. v2i32 -> v8i32 to match v8f64).
19576 MVT WideExpVT =
19577 MVT::getVectorVT(Exp.getSimpleValueType().getVectorElementType(),
19579 SDValue WideExp = widenSubVector(WideExpVT, Exp, /*ZeroNewElements=*/true,
19580 Subtarget, DAG, DL);
19581 SDValue WideExpFp =
19582 DAG.getNode(ISD::SINT_TO_FP, DL, WideX.getValueType(), WideExp);
19583 SDValue Scalef =
19584 DAG.getNode(X86ISD::SCALEF, DL, WideX.getValueType(), WideX, WideExpFp);
19585 SDValue Final =
19586 DAG.getExtractSubvector(DL, X.getSimpleValueType(), Scalef, 0);
19587 return DAG.getFPExtendOrRound(Final, DL, XTy);
19588}
19589
19591 SelectionDAG &DAG) {
19592 SDLoc dl(Op);
19593 MVT OpVT = Op.getSimpleValueType();
19594
19595 // It's always cheaper to replace a xor+movd with xorps and simplifies further
19596 // combines.
19597 if (X86::isZeroNode(Op.getOperand(0)))
19598 return getZeroVector(OpVT, Subtarget, DAG, dl);
19599
19600 // If this is a 256-bit vector result, first insert into a 128-bit
19601 // vector and then insert into the 256-bit vector.
19602 if (!OpVT.is128BitVector()) {
19603 // Insert into a 128-bit vector.
19604 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
19606 OpVT.getVectorNumElements() / SizeFactor);
19607
19608 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
19609
19610 // Insert the 128-bit vector.
19611 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
19612 }
19613 assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
19614 "Expected an SSE type!");
19615
19616 // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
19617 // tblgen.
19618 if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
19619 return Op;
19620
19621 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
19622 return DAG.getBitcast(
19623 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
19624}
19625
19626// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
19627// simple superregister reference or explicit instructions to insert
19628// the upper bits of a vector.
19630 SelectionDAG &DAG) {
19631 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
19632
19633 return insert1BitVector(Op, DAG, Subtarget);
19634}
19635
19637 SelectionDAG &DAG) {
19638 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
19639 "Only vXi1 extract_subvectors need custom lowering");
19640
19641 SDLoc dl(Op);
19642 SDValue Vec = Op.getOperand(0);
19643 uint64_t IdxVal = Op.getConstantOperandVal(1);
19644
19645 if (IdxVal == 0) // the operation is legal
19646 return Op;
19647
19648 // Extend to natively supported kshift.
19649 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19650
19651 // Shift to the LSB.
19652 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19653 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19654
19655 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19656 DAG.getVectorIdxConstant(0, dl));
19657}
19658
19659// Returns the appropriate wrapper opcode for a global reference.
19660unsigned X86TargetLowering::getGlobalWrapperKind(
19661 const GlobalValue *GV, const unsigned char OpFlags) const {
19662 // References to absolute symbols are never PC-relative.
19663 if (GV && GV->isAbsoluteSymbolRef())
19664 return X86ISD::Wrapper;
19665
19666 // The following OpFlags under RIP-rel PIC use RIP.
19667 if (Subtarget.isPICStyleRIPRel() &&
19668 (OpFlags == X86II::MO_NO_FLAG || OpFlags == X86II::MO_COFFSTUB ||
19669 OpFlags == X86II::MO_DLLIMPORT))
19670 return X86ISD::WrapperRIP;
19671
19672 // GOTPCREL references must always use RIP.
19673 if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
19674 return X86ISD::WrapperRIP;
19675
19676 return X86ISD::Wrapper;
19677}
19678
19679// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19680// their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19681// one of the above mentioned nodes. It has to be wrapped because otherwise
19682// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19683// be used to form addressing mode. These wrapped nodes will be selected
19684// into MOV32ri.
19685SDValue
19686X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19687 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19688
19689 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19690 // global base reg.
19691 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19692
19693 auto PtrVT = getPointerTy(DAG.getDataLayout());
19694 SDValue Result = DAG.getTargetConstantPool(
19695 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19696 SDLoc DL(CP);
19697 Result =
19698 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19699 // With PIC, the address is actually $g + Offset.
19700 if (OpFlag) {
19701 Result =
19702 DAG.getNode(ISD::ADD, DL, PtrVT,
19703 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19704 }
19705
19706 return Result;
19707}
19708
19709SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19710 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19711
19712 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19713 // global base reg.
19714 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19715
19716 EVT PtrVT = Op.getValueType();
19717 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19718 SDLoc DL(JT);
19719 Result =
19720 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19721
19722 // With PIC, the address is actually $g + Offset.
19723 if (OpFlag)
19724 Result =
19725 DAG.getNode(ISD::ADD, DL, PtrVT,
19726 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19727
19728 return Result;
19729}
19730
19731SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19732 SelectionDAG &DAG) const {
19733 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19734}
19735
19736SDValue
19737X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19738 // Create the TargetBlockAddressAddress node.
19739 unsigned char OpFlags =
19740 Subtarget.classifyBlockAddressReference();
19741 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19742 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19743 SDLoc dl(Op);
19744 EVT PtrVT = Op.getValueType();
19745 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19746 Result =
19747 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlags), dl, PtrVT, Result);
19748
19749 // With PIC, the address is actually $g + Offset.
19750 if (isGlobalRelativeToPICBase(OpFlags)) {
19751 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19752 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19753 }
19754
19755 return Result;
19756}
19757
19758/// Creates target global address or external symbol nodes for calls or
19759/// other uses.
19760SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19761 bool ForCall,
19762 bool *IsImpCall) const {
19763 // Unpack the global address or external symbol.
19764 SDLoc dl(Op);
19765 const GlobalValue *GV = nullptr;
19766 int64_t Offset = 0;
19767 const char *ExternalSym = nullptr;
19768 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19769 GV = G->getGlobal();
19770 Offset = G->getOffset();
19771 } else {
19772 const auto *ES = cast<ExternalSymbolSDNode>(Op);
19773 ExternalSym = ES->getSymbol();
19774 }
19775
19776 // Calculate some flags for address lowering.
19778 unsigned char OpFlags;
19779 if (ForCall)
19780 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19781 else
19782 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19783 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19784 bool NeedsLoad = isGlobalStubReference(OpFlags);
19785
19787 EVT PtrVT = Op.getValueType();
19788 SDValue Result;
19789
19790 if (GV) {
19791 // Create a target global address if this is a global. If possible, fold the
19792 // offset into the global address reference. Otherwise, ADD it on later.
19793 // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19794 // allowed because if the address of foo is 0, the ELF R_X86_64_32
19795 // relocation will compute to a negative value, which is invalid.
19796 int64_t GlobalOffset = 0;
19797 if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19799 std::swap(GlobalOffset, Offset);
19800 }
19801 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19802 } else {
19803 // If this is not a global address, this must be an external symbol.
19804 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19805 }
19806
19807 // If this is a direct call, avoid the wrapper if we don't need to do any
19808 // loads or adds. This allows SDAG ISel to match direct calls.
19809 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19810 return Result;
19811
19812 // If Import Call Optimization is enabled and this is an imported function
19813 // then make a note of it and return the global address without wrapping.
19814 if (IsImpCall && (OpFlags == X86II::MO_DLLIMPORT) &&
19815 Mod.getModuleFlag("import-call-optimization")) {
19816 assert(ForCall && "Should only enable import call optimization if we are "
19817 "lowering a call");
19818 *IsImpCall = true;
19819 return Result;
19820 }
19821
19822 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19823
19824 // With PIC, the address is actually $g + Offset.
19825 if (HasPICReg) {
19826 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19827 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19828 }
19829
19830 // For globals that require a load from a stub to get the address, emit the
19831 // load.
19832 if (NeedsLoad)
19833 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19835
19836 // If there was a non-zero offset that we didn't fold, create an explicit
19837 // addition for it.
19838 if (Offset != 0)
19839 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19840 DAG.getSignedConstant(Offset, dl, PtrVT));
19841
19842 return Result;
19843}
19844
19845SDValue
19846X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19847 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19848}
19849
19851 const EVT PtrVT, unsigned ReturnReg,
19852 unsigned char OperandFlags,
19853 bool LoadGlobalBaseReg = false,
19854 bool LocalDynamic = false) {
19856 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19857 SDLoc dl(GA);
19858 SDValue TGA;
19859 bool UseTLSDESC = DAG.getTarget().useTLSDESC();
19860 SDValue Chain = DAG.getEntryNode();
19861 SDValue Ret;
19862 if (LocalDynamic && UseTLSDESC) {
19863 TGA = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, OperandFlags);
19864 // Reuse existing GetTLSADDR node if we can find it.
19865 if (TGA->hasOneUse()) {
19866 // TLSDESC uses TGA.
19867 SDNode *TLSDescOp = *TGA->user_begin();
19868 assert(TLSDescOp->getOpcode() == X86ISD::TLSDESC &&
19869 "Unexpected TLSDESC DAG");
19870 // CALLSEQ_END uses TGA via a chain and glue.
19871 auto *CallSeqEndOp = TLSDescOp->getGluedUser();
19872 assert(CallSeqEndOp && CallSeqEndOp->getOpcode() == ISD::CALLSEQ_END &&
19873 "Unexpected TLSDESC DAG");
19874 // CopyFromReg uses CALLSEQ_END via a chain and glue.
19875 auto *CopyFromRegOp = CallSeqEndOp->getGluedUser();
19876 assert(CopyFromRegOp && CopyFromRegOp->getOpcode() == ISD::CopyFromReg &&
19877 "Unexpected TLSDESC DAG");
19878 Ret = SDValue(CopyFromRegOp, 0);
19879 }
19880 } else {
19881 TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19882 GA->getOffset(), OperandFlags);
19883 }
19884
19885 if (!Ret) {
19886 unsigned CallType = UseTLSDESC ? X86ISD::TLSDESC
19887 : LocalDynamic ? X86ISD::TLSBASEADDR
19888 : X86ISD::TLSADDR;
19889
19890 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
19891 if (LoadGlobalBaseReg) {
19892 SDValue InGlue;
19893 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
19894 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT),
19895 InGlue);
19896 InGlue = Chain.getValue(1);
19897 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA, InGlue});
19898 } else {
19899 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA});
19900 }
19901 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), dl);
19902
19903 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19904 MFI.setHasCalls(true);
19905
19906 SDValue Glue = Chain.getValue(1);
19907 Ret = DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
19908 }
19909
19910 if (!UseTLSDESC)
19911 return Ret;
19912
19913 const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
19914 unsigned Seg = Subtarget.is64Bit() ? X86AS::FS : X86AS::GS;
19915
19917 SDValue Offset =
19918 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19919 MachinePointerInfo(Ptr));
19920 return DAG.getNode(ISD::ADD, dl, PtrVT, Ret, Offset);
19921}
19922
19923// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19924static SDValue
19926 const EVT PtrVT) {
19927 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD,
19928 /*LoadGlobalBaseReg=*/true);
19929}
19930
19931// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19932static SDValue
19934 const EVT PtrVT) {
19935 return GetTLSADDR(DAG, GA, PtrVT, X86::RAX, X86II::MO_TLSGD);
19936}
19937
19938// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19939static SDValue
19941 const EVT PtrVT) {
19942 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD);
19943}
19944
19946 SelectionDAG &DAG, const EVT PtrVT,
19947 bool Is64Bit, bool Is64BitLP64) {
19948 SDLoc dl(GA);
19949
19950 // Get the start address of the TLS block for this module.
19954
19955 SDValue Base;
19956 if (Is64Bit) {
19957 unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19958 Base = GetTLSADDR(DAG, GA, PtrVT, ReturnReg, X86II::MO_TLSLD,
19959 /*LoadGlobalBaseReg=*/false,
19960 /*LocalDynamic=*/true);
19961 } else {
19962 Base = GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSLDM,
19963 /*LoadGlobalBaseReg=*/true,
19964 /*LocalDynamic=*/true);
19965 }
19966
19967 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19968 // of Base.
19969
19970 // Build x@dtpoff.
19971 unsigned char OperandFlags = X86II::MO_DTPOFF;
19972 unsigned WrapperKind = X86ISD::Wrapper;
19973 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19974 GA->getValueType(0),
19975 GA->getOffset(), OperandFlags);
19976 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19977
19978 // Add x@dtpoff with the base.
19979 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19980}
19981
19982// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19984 const EVT PtrVT, TLSModel::Model model,
19985 bool is64Bit, bool isPIC) {
19986 SDLoc dl(GA);
19987
19988 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
19991
19992 SDValue ThreadPointer =
19993 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19994 MachinePointerInfo(Ptr));
19995
19996 unsigned char OperandFlags = 0;
19997 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
19998 // initialexec.
19999 unsigned WrapperKind = X86ISD::Wrapper;
20000 if (model == TLSModel::LocalExec) {
20001 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
20002 } else if (model == TLSModel::InitialExec) {
20003 if (is64Bit) {
20004 OperandFlags = X86II::MO_GOTTPOFF;
20005 WrapperKind = X86ISD::WrapperRIP;
20006 } else {
20007 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
20008 }
20009 } else {
20010 llvm_unreachable("Unexpected model");
20011 }
20012
20013 // emit "addl x@ntpoff,%eax" (local exec)
20014 // or "addl x@indntpoff,%eax" (initial exec)
20015 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
20016 SDValue TGA =
20017 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
20018 GA->getOffset(), OperandFlags);
20019 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20020
20021 if (model == TLSModel::InitialExec) {
20022 if (isPIC && !is64Bit) {
20023 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
20024 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20025 Offset);
20026 }
20027
20028 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
20030 }
20031
20032 // The address of the thread local variable is the add of the thread
20033 // pointer with the offset of the variable.
20034 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
20035}
20036
20037SDValue
20038X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
20039
20040 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
20041
20042 if (DAG.getTarget().useEmulatedTLS())
20043 return LowerToTLSEmulatedModel(GA, DAG);
20044
20045 const GlobalValue *GV = GA->getGlobal();
20046 EVT PtrVT = Op.getValueType();
20047 bool PositionIndependent = isPositionIndependent();
20048
20049 if (Subtarget.isTargetELF()) {
20050 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
20051 // LFI does not support dlopen, so all TLS can be statically resolved. We
20052 // automatically upgrade dynamic models to InitialExec because the dynamic
20053 // TLS sequences are slower than necessary and interact poorly with LFI
20054 // rewriting combined with rewrites from linker relaxation.
20055 if (Subtarget.isLFI())
20056 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic)
20057 model = TLSModel::InitialExec;
20058 switch (model) {
20060 if (Subtarget.is64Bit()) {
20061 if (Subtarget.isTarget64BitLP64())
20062 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
20063 return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
20064 }
20065 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
20067 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
20068 Subtarget.isTarget64BitLP64());
20071 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
20072 PositionIndependent);
20073 }
20074 llvm_unreachable("Unknown TLS model.");
20075 }
20076
20077 if (Subtarget.isTargetDarwin()) {
20078 // Darwin only has one model of TLS. Lower to that.
20079 unsigned char OpFlag = 0;
20080 unsigned WrapperKind = 0;
20081
20082 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20083 // global base reg.
20084 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
20085 if (PIC32) {
20086 OpFlag = X86II::MO_TLVP_PIC_BASE;
20087 WrapperKind = X86ISD::Wrapper;
20088 } else {
20089 OpFlag = X86II::MO_TLVP;
20090 WrapperKind = X86ISD::WrapperRIP;
20091 }
20092 SDLoc DL(Op);
20093 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
20094 GA->getValueType(0),
20095 GA->getOffset(), OpFlag);
20096 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
20097
20098 // With PIC32, the address is actually $g + Offset.
20099 if (PIC32)
20100 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
20101 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20102 Offset);
20103
20104 // Lowering the machine isd will make sure everything is in the right
20105 // location.
20106 SDValue Chain = DAG.getEntryNode();
20107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20108 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
20109 SDValue Args[] = { Chain, Offset };
20110 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
20111 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
20112
20113 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
20114 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20115 MFI.setAdjustsStack(true);
20116
20117 // And our return value (tls address) is in the standard call return value
20118 // location.
20119 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
20120 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
20121 }
20122
20123 if (Subtarget.isOSWindows()) {
20124 // Just use the implicit TLS architecture
20125 // Need to generate something similar to:
20126 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
20127 // ; from TEB
20128 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
20129 // mov rcx, qword [rdx+rcx*8]
20130 // mov eax, .tls$:tlsvar
20131 // [rax+rcx] contains the address
20132 // Windows 64bit: gs:0x58
20133 // Windows 32bit: fs:__tls_array
20134
20135 SDLoc dl(GA);
20136 SDValue Chain = DAG.getEntryNode();
20137
20138 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
20139 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
20140 // use its literal value of 0x2C.
20142 Subtarget.is64Bit() ? PointerType::get(*DAG.getContext(), X86AS::GS)
20144
20145 SDValue TlsArray = Subtarget.is64Bit()
20146 ? DAG.getIntPtrConstant(0x58, dl)
20147 : (Subtarget.isTargetWindowsGNU()
20148 ? DAG.getIntPtrConstant(0x2C, dl)
20149 : DAG.getExternalSymbol("_tls_array", PtrVT));
20150
20151 SDValue ThreadPointer =
20152 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
20153
20154 SDValue res;
20156 res = ThreadPointer;
20157 } else {
20158 // Load the _tls_index variable
20159 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
20160 if (Subtarget.is64Bit())
20161 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
20162 MachinePointerInfo(), MVT::i32);
20163 else
20164 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
20165
20166 const DataLayout &DL = DAG.getDataLayout();
20167 SDValue Scale =
20168 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
20169 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
20170
20171 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
20172 }
20173
20174 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
20175
20176 // Get the offset of start of .tls section
20177 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20178 GA->getValueType(0),
20180 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
20181
20182 // The address of the thread local variable is the add of the thread
20183 // pointer with the offset of the variable.
20184 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
20185 }
20186
20187 llvm_unreachable("TLS not implemented for this target.");
20188}
20189
20191 if (Subtarget.is64Bit() && Subtarget.isTargetELF()) {
20192 const TargetMachine &TM = getTargetMachine();
20193 TLSModel::Model Model = TM.getTLSModel(&GV);
20194 switch (Model) {
20197 // We can include the %fs segment register in addressing modes.
20198 return true;
20201 // These models do not result in %fs relative addresses unless
20202 // TLS descriptior are used.
20203 //
20204 // Even in the case of TLS descriptors we currently have no way to model
20205 // the difference between %fs access and the computations needed for the
20206 // offset and returning `true` for TLS-desc currently duplicates both
20207 // which is detrimental :-/
20208 return false;
20209 }
20210 }
20211 return false;
20212}
20213
20214/// Lower SRA_PARTS and friends, which return two i32 values
20215/// and take a 2 x i32 value to shift plus a shift amount.
20216/// TODO: Can this be moved to general expansion code?
20218 SDValue Lo, Hi;
20219 DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
20220 return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
20221}
20222
20223// Try to use a packed vector operation to handle i64 on 32-bit targets when
20224// AVX512DQ is enabled.
20226 SelectionDAG &DAG,
20227 const X86Subtarget &Subtarget) {
20228 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20229 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20230 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20231 Op.getOpcode() == ISD::UINT_TO_FP) &&
20232 "Unexpected opcode!");
20233 bool IsStrict = Op->isStrictFPOpcode();
20234 unsigned OpNo = IsStrict ? 1 : 0;
20235 SDValue Src = Op.getOperand(OpNo);
20236 MVT SrcVT = Src.getSimpleValueType();
20237 MVT VT = Op.getSimpleValueType();
20238
20239 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
20240 (VT != MVT::f32 && VT != MVT::f64))
20241 return SDValue();
20242
20243 // Pack the i64 into a vector, do the operation and extract.
20244
20245 // Using 256-bit to ensure result is 128-bits for f32 case.
20246 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
20247 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
20248 MVT VecVT = MVT::getVectorVT(VT, NumElts);
20249
20250 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
20251 if (IsStrict) {
20252 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
20253 {Op.getOperand(0), InVec});
20254 SDValue Chain = CvtVec.getValue(1);
20255 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20256 DAG.getVectorIdxConstant(0, dl));
20257 return DAG.getMergeValues({Value, Chain}, dl);
20258 }
20259
20260 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
20261
20262 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20263 DAG.getVectorIdxConstant(0, dl));
20264}
20265
20266// Try to use a packed vector operation to handle i64 on 32-bit targets.
20268 const X86Subtarget &Subtarget) {
20269 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20270 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20271 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20272 Op.getOpcode() == ISD::UINT_TO_FP) &&
20273 "Unexpected opcode!");
20274 bool IsStrict = Op->isStrictFPOpcode();
20275 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20276 MVT SrcVT = Src.getSimpleValueType();
20277 MVT VT = Op.getSimpleValueType();
20278
20279 if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
20280 return SDValue();
20281
20282 // Pack the i64 into a vector, do the operation and extract.
20283
20284 assert(Subtarget.hasFP16() && "Expected FP16");
20285
20286 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
20287 if (IsStrict) {
20288 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
20289 {Op.getOperand(0), InVec});
20290 SDValue Chain = CvtVec.getValue(1);
20291 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20292 DAG.getVectorIdxConstant(0, dl));
20293 return DAG.getMergeValues({Value, Chain}, dl);
20294 }
20295
20296 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
20297
20298 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20299 DAG.getVectorIdxConstant(0, dl));
20300}
20301
20302static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
20303 const X86Subtarget &Subtarget) {
20304 switch (Opcode) {
20305 case ISD::SINT_TO_FP:
20306 // TODO: Handle wider types with AVX/AVX512.
20307 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
20308 return false;
20309 // CVTDQ2PS or (V)CVTDQ2PD
20310 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
20311
20312 case ISD::UINT_TO_FP:
20313 // TODO: Handle wider types and i64 elements.
20314 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
20315 return false;
20316 // VCVTUDQ2PS or VCVTUDQ2PD
20317 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
20318
20319 default:
20320 return false;
20321 }
20322}
20323
20324/// Given a scalar cast operation that is extracted from a vector, try to
20325/// vectorize the cast op followed by extraction. This will avoid an expensive
20326/// round-trip between XMM and GPR.
20328 SelectionDAG &DAG,
20329 const X86Subtarget &Subtarget) {
20330 // TODO: This could be enhanced to handle smaller integer types by peeking
20331 // through an extend.
20332 SDValue Extract = Cast.getOperand(0);
20333 MVT DestVT = Cast.getSimpleValueType();
20334 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20335 !isa<ConstantSDNode>(Extract.getOperand(1)))
20336 return SDValue();
20337
20338 // See if we have a 128-bit vector cast op for this type of cast.
20339 SDValue VecOp = Extract.getOperand(0);
20340 EVT FromVT = VecOp.getValueType();
20341 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
20342 MVT Vec128VT =
20343 MVT::getVectorVT(FromVT.getScalarType().getSimpleVT(), NumEltsInXMM);
20344 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
20345 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
20346 return SDValue();
20347
20348 // If we are extracting from a non-zero element, first shuffle the source
20349 // vector to allow extracting from element zero.
20350 if (!isNullConstant(Extract.getOperand(1))) {
20351 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
20352 Mask[0] = Extract.getConstantOperandVal(1);
20353 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
20354 }
20355 // If the source vector is wider than 128-bits, extract the low part. Do not
20356 // create an unnecessarily wide vector cast op.
20357 if (FromVT != Vec128VT)
20358 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
20359
20360 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
20361 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
20362 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
20363 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
20364 DAG.getVectorIdxConstant(0, DL));
20365}
20366
20367/// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
20368/// try to vectorize the cast ops. This will avoid an expensive round-trip
20369/// between XMM and GPR.
20370static SDValue lowerFPToIntToFP(SDValue CastToFP, const SDLoc &DL,
20371 SelectionDAG &DAG,
20372 const X86Subtarget &Subtarget) {
20373 SDValue CastToInt = CastToFP.getOperand(0);
20374 MVT VT = CastToFP.getSimpleValueType();
20375 if ((CastToFP.getOpcode() != ISD::SINT_TO_FP &&
20376 CastToFP.getOpcode() != ISD::UINT_TO_FP) ||
20377 (CastToInt.getOpcode() != ISD::FP_TO_SINT &&
20378 CastToInt.getOpcode() != ISD::FP_TO_UINT) ||
20379 VT.isVector())
20380 return SDValue();
20381
20382 MVT IntVT = CastToInt.getSimpleValueType();
20383 SDValue X = CastToInt.getOperand(0);
20384 MVT SrcVT = X.getSimpleValueType();
20385 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
20386 return SDValue();
20387
20388 // See if we have 128-bit vector cast instructions for this type of cast.
20389 // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
20390 if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
20391 (IntVT != MVT::i32 && IntVT != MVT::i64))
20392 return SDValue();
20393
20394 unsigned SrcSize = SrcVT.getSizeInBits();
20395 unsigned IntSize = IntVT.getSizeInBits();
20396 unsigned VTSize = VT.getSizeInBits();
20397 bool FromUnsigned = CastToFP.getOpcode() == ISD::UINT_TO_FP;
20398 bool ToUnsigned = CastToInt.getOpcode() == ISD::FP_TO_UINT;
20399 unsigned ToIntOpcode =
20400 SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
20401 unsigned ToFPOpcode =
20402 IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
20403 unsigned Width = 128;
20404
20405 if (Subtarget.hasVLX() && Subtarget.hasDQI()) {
20406 // AVX512DQ+VLX
20407 if (ToUnsigned) {
20408 ToIntOpcode =
20409 SrcSize != IntSize ? X86ISD::CVTTP2UI : (unsigned)ISD::FP_TO_UINT;
20410 }
20411 if (FromUnsigned) {
20412 ToFPOpcode =
20413 IntSize != VTSize ? X86ISD::CVTUI2P : (unsigned)ISD::UINT_TO_FP;
20414 }
20415 } else {
20416 if (FromUnsigned || ToUnsigned || IntVT == MVT::i64) {
20417 // SSE2 can only perform f64/f32 <-> i32 signed.
20418 if (!Subtarget.useAVX512Regs() || !Subtarget.hasDQI())
20419 return SDValue();
20420
20421 // Need to extend width for AVX512DQ without AVX512VL.
20422 Width = 512;
20423 ToIntOpcode = CastToInt.getOpcode();
20424 ToFPOpcode = FromUnsigned ? ISD::UINT_TO_FP : ISD::SINT_TO_FP;
20425 }
20426 }
20427
20428 MVT VecSrcVT, VecIntVT, VecVT;
20429 unsigned NumElts;
20430 unsigned SrcElts, VTElts;
20431 // Some conversions are only legal with uniform vector sizes on AVX512DQ.
20432 if (Width == 512) {
20433 NumElts = std::min(Width / IntSize, Width / SrcSize);
20434 SrcElts = NumElts;
20435 VTElts = NumElts;
20436 } else {
20437 NumElts = Width / IntSize;
20438 SrcElts = Width / SrcSize;
20439 VTElts = Width / VTSize;
20440 }
20441 VecIntVT = MVT::getVectorVT(IntVT, NumElts);
20442 VecSrcVT = MVT::getVectorVT(SrcVT, SrcElts);
20443 VecVT = MVT::getVectorVT(VT, VTElts);
20444 // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
20445 //
20446 // We are not defining the high elements (for example, zero them) because
20447 // that could nullify any performance advantage that we hoped to gain from
20448 // this vector op hack. We do not expect any adverse effects (like denorm
20449 // penalties) with cast ops.
20450 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
20451 SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
20452 SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
20453 SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
20454 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
20455}
20456
20458 SelectionDAG &DAG,
20459 const X86Subtarget &Subtarget) {
20460 bool IsStrict = Op->isStrictFPOpcode();
20461 MVT VT = Op->getSimpleValueType(0);
20462 SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
20463
20464 if (Subtarget.hasDQI()) {
20465 assert(!Subtarget.hasVLX() && "Unexpected features");
20466
20467 assert((Src.getSimpleValueType() == MVT::v2i64 ||
20468 Src.getSimpleValueType() == MVT::v4i64) &&
20469 "Unsupported custom type");
20470
20471 // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
20472 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
20473 "Unexpected VT!");
20474 MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20475
20476 // Need to concat with zero vector for strict fp to avoid spurious
20477 // exceptions.
20478 SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
20479 : DAG.getUNDEF(MVT::v8i64);
20480 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
20481 DAG.getVectorIdxConstant(0, DL));
20482 SDValue Res, Chain;
20483 if (IsStrict) {
20484 Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
20485 {Op->getOperand(0), Src});
20486 Chain = Res.getValue(1);
20487 } else {
20488 Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
20489 }
20490
20491 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20492 DAG.getVectorIdxConstant(0, DL));
20493
20494 if (IsStrict)
20495 return DAG.getMergeValues({Res, Chain}, DL);
20496 return Res;
20497 }
20498
20499 bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
20500 Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
20501 if (VT != MVT::v4f32 || IsSigned)
20502 return SDValue();
20503
20504 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
20505 SDValue One = DAG.getConstant(1, DL, MVT::v4i64);
20506 SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
20507 DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
20508 DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
20509 SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
20510 SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
20511 SmallVector<SDValue, 4> SignCvts(4);
20512 SmallVector<SDValue, 4> Chains(4);
20513 for (int i = 0; i != 4; ++i) {
20514 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
20515 DAG.getVectorIdxConstant(i, DL));
20516 if (IsStrict) {
20517 SignCvts[i] =
20518 DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
20519 {Op.getOperand(0), Elt});
20520 Chains[i] = SignCvts[i].getValue(1);
20521 } else {
20522 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
20523 }
20524 }
20525 SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
20526
20527 SDValue Slow, Chain;
20528 if (IsStrict) {
20529 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
20530 Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
20531 {Chain, SignCvt, SignCvt});
20532 Chain = Slow.getValue(1);
20533 } else {
20534 Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
20535 }
20536
20537 IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
20538 SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
20539
20540 if (IsStrict)
20541 return DAG.getMergeValues({Cvt, Chain}, DL);
20542
20543 return Cvt;
20544}
20545
20547 SelectionDAG &DAG) {
20548 bool IsStrict = Op->isStrictFPOpcode();
20549 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20550 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20551 MVT VT = Op.getSimpleValueType();
20552 MVT NVT = VT.changeElementType(MVT::f32);
20553
20554 SDValue Rnd = DAG.getIntPtrConstant(0, dl, /*isTarget=*/true);
20555 if (IsStrict)
20556 return DAG.getNode(
20557 ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
20558 {Chain,
20559 DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
20560 Rnd});
20561 return DAG.getNode(ISD::FP_ROUND, dl, VT,
20562 DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
20563}
20564
20565static bool isLegalConversion(MVT VT, MVT FloatVT, bool IsSigned,
20566 const X86Subtarget &Subtarget) {
20567 if (FloatVT.getScalarType() != MVT::f16 || Subtarget.hasVLX()) {
20568 if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
20569 return true;
20570 if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
20571 return true;
20572 }
20573 if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
20574 return true;
20575 if (Subtarget.useAVX512Regs()) {
20576 if (VT == MVT::v16i32)
20577 return true;
20578 if (VT == MVT::v8i64 && FloatVT == MVT::v8f16 && Subtarget.hasFP16())
20579 return true;
20580 if (VT == MVT::v8i64 && Subtarget.hasDQI())
20581 return true;
20582 }
20583 if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
20584 (VT == MVT::v2i64 || VT == MVT::v4i64))
20585 return true;
20586 return false;
20587}
20588
20589SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20590 SelectionDAG &DAG) const {
20591 bool IsStrict = Op->isStrictFPOpcode();
20592 unsigned OpNo = IsStrict ? 1 : 0;
20593 SDValue Src = Op.getOperand(OpNo);
20594 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20595 MVT SrcVT = Src.getSimpleValueType();
20596 MVT VT = Op.getSimpleValueType();
20597 SDLoc dl(Op);
20598
20599 if (isBF16orSoftF16(VT, Subtarget))
20600 return promoteXINT_TO_FP(Op, dl, DAG);
20601 else if (isLegalConversion(SrcVT, VT, true, Subtarget))
20602 return Op;
20603
20604 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
20605 return LowerWin64_INT128_TO_FP(Op, DAG);
20606
20607 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
20608 return Extract;
20609
20610 if (SDValue R = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
20611 return R;
20612
20613 if (SrcVT.isVector()) {
20614 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
20615 // Note: Since v2f64 is a legal type. We don't need to zero extend the
20616 // source for strict FP.
20617 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20618 DAG.getUNDEF(SrcVT));
20619 if (IsStrict)
20620 return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
20621 {Chain, Src});
20622 return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Src);
20623 }
20624 if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
20625 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
20626
20627 return SDValue();
20628 }
20629
20630 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
20631 "Unknown SINT_TO_FP to lower!");
20632
20633 bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
20634
20635 // These are really Legal; return the operand so the caller accepts it as
20636 // Legal.
20637 if (SrcVT == MVT::i32 && UseSSEReg)
20638 return Op;
20639 if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
20640 return Op;
20641
20642 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
20643 return V;
20644 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
20645 return V;
20646
20647 // SSE doesn't have an i16 conversion so we need to promote.
20648 if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
20649 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
20650 if (IsStrict)
20651 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
20652 {Chain, Ext});
20653
20654 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
20655 }
20656
20657 if (VT == MVT::f128 || !Subtarget.hasX87())
20658 return SDValue();
20659
20660 SDValue ValueToStore = Src;
20661 if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
20662 // Bitcasting to f64 here allows us to do a single 64-bit store from
20663 // an SSE register, avoiding the store forwarding penalty that would come
20664 // with two 32-bit stores.
20665 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20666
20667 unsigned Size = SrcVT.getStoreSize();
20670 auto PtrVT = getPointerTy(MF.getDataLayout());
20671 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
20672 MachinePointerInfo MPI =
20674 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20675 Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
20676 std::pair<SDValue, SDValue> Tmp =
20677 BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
20678
20679 if (IsStrict)
20680 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20681
20682 return Tmp.first;
20683}
20684
20685std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
20686 EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
20687 MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
20688 // Build the FILD
20689 SDVTList Tys;
20690 bool useSSE = isScalarFPTypeInSSEReg(DstVT);
20691 if (useSSE)
20692 Tys = DAG.getVTList(MVT::f80, MVT::Other);
20693 else
20694 Tys = DAG.getVTList(DstVT, MVT::Other);
20695
20696 SDValue FILDOps[] = {Chain, Pointer};
20697 SDValue Result =
20698 DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
20699 Alignment, MachineMemOperand::MOLoad);
20700 Chain = Result.getValue(1);
20701
20702 if (useSSE) {
20704 unsigned SSFISize = DstVT.getStoreSize();
20705 // The slot is private, so ABI alignment is enough. More might realign the
20706 // frame.
20707 Align SlotAlign = DAG.getEVTAlign(DstVT);
20708 int SSFI = MF.getFrameInfo().CreateStackObject(SSFISize, SlotAlign, false);
20709 auto PtrVT = getPointerTy(MF.getDataLayout());
20710 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20711 Tys = DAG.getVTList(MVT::Other);
20712 SDValue FSTOps[] = {Chain, Result, StackSlot};
20715 MachineMemOperand::MOStore, SSFISize, SlotAlign);
20716
20717 Chain =
20718 DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
20719 Result = DAG.getLoad(
20720 DstVT, DL, Chain, StackSlot,
20722 SlotAlign);
20723 Chain = Result.getValue(1);
20724 }
20725
20726 return { Result, Chain };
20727}
20728
20729/// Horizontal vector math instructions may be slower than normal math with
20730/// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
20731/// implementation, and likely shuffle complexity of the alternate sequence.
20732static bool shouldUseHorizontalOp(bool IsSingleSource, const SelectionDAG &DAG,
20733 const X86Subtarget &Subtarget) {
20734 bool IsOptimizingSize = DAG.shouldOptForSize();
20735 bool HasFastHOps = Subtarget.hasFastHorizontalOps();
20736 return !IsSingleSource || IsOptimizingSize || HasFastHOps;
20737}
20738
20739/// 64-bit unsigned integer to double expansion.
20741 SelectionDAG &DAG,
20742 const X86Subtarget &Subtarget) {
20743 // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
20744 // when converting 0 when rounding toward negative infinity. Caller will
20745 // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
20746 assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
20747 // This algorithm is not obvious. Here it is what we're trying to output:
20748 /*
20749 movq %rax, %xmm0
20750 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
20751 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
20752 #ifdef __SSE3__
20753 haddpd %xmm0, %xmm0
20754 #else
20755 pshufd $0x4e, %xmm0, %xmm1
20756 addpd %xmm1, %xmm0
20757 #endif
20758 */
20759
20760 LLVMContext *Context = DAG.getContext();
20761
20762 // Build some magic constants.
20763 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
20764 Constant *C0 = ConstantDataVector::get(*Context, CV0);
20765 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20766 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
20767
20769 CV1.push_back(
20770 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20771 APInt(64, 0x4330000000000000ULL))));
20772 CV1.push_back(
20773 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20774 APInt(64, 0x4530000000000000ULL))));
20775 Constant *C1 = ConstantVector::get(CV1);
20776 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
20777
20778 // Load the 64-bit value into an XMM register.
20779 SDValue XR1 =
20780 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
20781 SDValue CLod0 = DAG.getLoad(
20782 MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
20784 SDValue Unpck1 =
20785 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
20786
20787 SDValue CLod1 = DAG.getLoad(
20788 MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
20790 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
20791 // TODO: Are there any fast-math-flags to propagate here?
20792 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
20793 SDValue Result;
20794
20795 if (Subtarget.hasSSE3() &&
20796 shouldUseHorizontalOp(true, DAG, Subtarget)) {
20797 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
20798 } else {
20799 SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
20800 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
20801 }
20802 Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
20803 DAG.getVectorIdxConstant(0, dl));
20804 return Result;
20805}
20806
20807/// 32-bit unsigned integer to float expansion.
20809 SelectionDAG &DAG,
20810 const X86Subtarget &Subtarget) {
20811 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20812 // FP constant to bias correct the final result.
20813 SDValue Bias = DAG.getConstantFP(
20814 llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::f64);
20815
20816 // Load the 32-bit value into an XMM register.
20817 SDValue Load =
20818 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
20819
20820 // Zero out the upper parts of the register.
20821 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
20822
20823 // Or the load with the bias.
20824 SDValue Or = DAG.getNode(
20825 ISD::OR, dl, MVT::v2i64,
20826 DAG.getBitcast(MVT::v2i64, Load),
20827 DAG.getBitcast(MVT::v2i64,
20828 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
20829 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
20830 DAG.getBitcast(MVT::v2f64, Or),
20831 DAG.getVectorIdxConstant(0, dl));
20832
20833 if (Op.getNode()->isStrictFPOpcode()) {
20834 // Subtract the bias.
20835 // TODO: Are there any fast-math-flags to propagate here?
20836 SDValue Chain = Op.getOperand(0);
20837 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
20838 {Chain, Or, Bias});
20839
20840 if (Op.getValueType() == Sub.getValueType())
20841 return Sub;
20842
20843 // Handle final rounding.
20844 std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
20845 Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
20846
20847 return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
20848 }
20849
20850 // Subtract the bias.
20851 // TODO: Are there any fast-math-flags to propagate here?
20852 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
20853
20854 // Handle final rounding.
20855 return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
20856}
20857
20859 SelectionDAG &DAG,
20860 const X86Subtarget &Subtarget) {
20861 if (Op.getSimpleValueType() != MVT::v2f64)
20862 return SDValue();
20863
20864 bool IsStrict = Op->isStrictFPOpcode();
20865
20866 SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
20867 assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
20868
20869 if (Subtarget.hasAVX512()) {
20870 if (!Subtarget.hasVLX()) {
20871 // Let generic type legalization widen this.
20872 if (!IsStrict)
20873 return SDValue();
20874 // Otherwise pad the integer input with 0s and widen the operation.
20875 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20876 DAG.getConstant(0, DL, MVT::v2i32));
20877 SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
20878 {Op.getOperand(0), N0});
20879 SDValue Chain = Res.getValue(1);
20880 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
20881 DAG.getVectorIdxConstant(0, DL));
20882 return DAG.getMergeValues({Res, Chain}, DL);
20883 }
20884
20885 // Legalize to v4i32 type.
20886 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20887 DAG.getUNDEF(MVT::v2i32));
20888 if (IsStrict)
20889 return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
20890 {Op.getOperand(0), N0});
20891 return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
20892 }
20893
20894 // Zero extend to 2i64, OR with the floating point representation of 2^52.
20895 // This gives us the floating point equivalent of 2^52 + the i32 integer
20896 // since double has 52-bits of mantissa. Then subtract 2^52 in floating
20897 // point leaving just our i32 integers in double format.
20898 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
20899 SDValue VBias = DAG.getConstantFP(
20900 llvm::bit_cast<double>(0x4330000000000000ULL), DL, MVT::v2f64);
20901 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
20902 DAG.getBitcast(MVT::v2i64, VBias));
20903 Or = DAG.getBitcast(MVT::v2f64, Or);
20904
20905 if (IsStrict)
20906 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
20907 {Op.getOperand(0), Or, VBias});
20908 return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
20909}
20910
20912 SelectionDAG &DAG,
20913 const X86Subtarget &Subtarget) {
20914 bool IsStrict = Op->isStrictFPOpcode();
20915 SDValue V = Op->getOperand(IsStrict ? 1 : 0);
20916 MVT VecIntVT = V.getSimpleValueType();
20917 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
20918 "Unsupported custom type");
20919
20920 if (Subtarget.hasAVX512()) {
20921 // With AVX512, but not VLX we need to widen to get a 512-bit result type.
20922 assert(!Subtarget.hasVLX() && "Unexpected features");
20923 MVT VT = Op->getSimpleValueType(0);
20924
20925 // v8i32->v8f64 is legal with AVX512 so just return it.
20926 if (VT == MVT::v8f64)
20927 return Op;
20928
20929 assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64 ||
20930 VT == MVT::v8f16) &&
20931 "Unexpected VT!");
20932 MVT WideVT = VT == MVT::v8f16 ? MVT::v16f16 : MVT::v16f32;
20933 MVT WideIntVT = MVT::v16i32;
20934 if (VT == MVT::v4f64) {
20935 WideVT = MVT::v8f64;
20936 WideIntVT = MVT::v8i32;
20937 }
20938
20939 // Need to concat with zero vector for strict fp to avoid spurious
20940 // exceptions.
20941 SDValue Tmp =
20942 IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
20943 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
20944 DAG.getVectorIdxConstant(0, DL));
20945 SDValue Res, Chain;
20946 if (IsStrict) {
20947 Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
20948 {Op->getOperand(0), V});
20949 Chain = Res.getValue(1);
20950 } else {
20951 Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
20952 }
20953
20954 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20955 DAG.getVectorIdxConstant(0, DL));
20956
20957 if (IsStrict)
20958 return DAG.getMergeValues({Res, Chain}, DL);
20959 return Res;
20960 }
20961
20962 if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
20963 Op->getSimpleValueType(0) == MVT::v4f64) {
20964 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
20965 Constant *Bias = ConstantFP::get(
20966 *DAG.getContext(),
20967 APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
20968 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20969 SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
20970 SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
20971 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
20972 SDValue VBias = DAG.getMemIntrinsicNode(
20973 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
20976
20977 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
20978 DAG.getBitcast(MVT::v4i64, VBias));
20979 Or = DAG.getBitcast(MVT::v4f64, Or);
20980
20981 if (IsStrict)
20982 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
20983 {Op.getOperand(0), Or, VBias});
20984 return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20985 }
20986
20987 // The algorithm is the following:
20988 // #ifdef __SSE4_1__
20989 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20990 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20991 // (uint4) 0x53000000, 0xaa);
20992 // #else
20993 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20994 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20995 // #endif
20996 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20997 // return (float4) lo + fhi;
20998
20999 bool Is128 = VecIntVT == MVT::v4i32;
21000 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
21001 // If we convert to something else than the supported type, e.g., to v4f64,
21002 // abort early.
21003 if (VecFloatVT != Op->getSimpleValueType(0))
21004 return SDValue();
21005
21006 // In the #idef/#else code, we have in common:
21007 // - The vector of constants:
21008 // -- 0x4b000000
21009 // -- 0x53000000
21010 // - A shift:
21011 // -- v >> 16
21012
21013 // Create the splat vector for 0x4b000000.
21014 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
21015 // Create the splat vector for 0x53000000.
21016 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
21017
21018 // Create the right shift.
21019 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
21020 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
21021
21022 SDValue Low, High;
21023 if (Subtarget.hasSSE41()) {
21024 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
21025 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
21026 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
21027 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
21028 // Low will be bitcasted right away, so do not bother bitcasting back to its
21029 // original type.
21030 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
21031 VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21032 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
21033 // (uint4) 0x53000000, 0xaa);
21034 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
21035 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
21036 // High will be bitcasted right away, so do not bother bitcasting back to
21037 // its original type.
21038 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
21039 VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21040 } else {
21041 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
21042 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
21043 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
21044 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
21045
21046 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
21047 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
21048 }
21049
21050 // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
21051 SDValue VecCstFSub = DAG.getConstantFP(
21052 APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
21053
21054 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
21055 // NOTE: By using fsub of a positive constant instead of fadd of a negative
21056 // constant, we avoid reassociation in MachineCombiner when reassoc is
21057 // enabled. See PR24512.
21058 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
21059 // TODO: Are there any fast-math-flags to propagate here?
21060 // (float4) lo;
21061 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
21062 // return (float4) lo + fhi;
21063 if (IsStrict) {
21064 SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
21065 {Op.getOperand(0), HighBitcast, VecCstFSub});
21066 return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
21067 {FHigh.getValue(1), LowBitcast, FHigh});
21068 }
21069
21070 SDValue FHigh =
21071 DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
21072 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
21073}
21074
21076 const X86Subtarget &Subtarget) {
21077 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
21078 SDValue N0 = Op.getOperand(OpNo);
21079 MVT SrcVT = N0.getSimpleValueType();
21080
21081 switch (SrcVT.SimpleTy) {
21082 default:
21083 llvm_unreachable("Custom UINT_TO_FP is not supported!");
21084 case MVT::v2i32:
21085 return lowerUINT_TO_FP_v2i32(Op, dl, DAG, Subtarget);
21086 case MVT::v4i32:
21087 case MVT::v8i32:
21088 return lowerUINT_TO_FP_vXi32(Op, dl, DAG, Subtarget);
21089 case MVT::v2i64:
21090 case MVT::v4i64:
21091 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
21092 }
21093}
21094
21095SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
21096 SelectionDAG &DAG) const {
21097 bool IsStrict = Op->isStrictFPOpcode();
21098 unsigned OpNo = IsStrict ? 1 : 0;
21099 SDValue Src = Op.getOperand(OpNo);
21100 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21101 auto PtrVT = getPointerTy(DAG.getDataLayout());
21102 MVT SrcVT = Src.getSimpleValueType();
21103 MVT DstVT = Op->getSimpleValueType(0);
21104 SDLoc dl(Op);
21105
21106 if (isBF16orSoftF16(DstVT, Subtarget))
21107 return promoteXINT_TO_FP(Op, dl, DAG);
21108 else if (isLegalConversion(SrcVT, DstVT, false, Subtarget))
21109 return Op;
21110
21111 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21112 return LowerWin64_INT128_TO_FP(Op, DAG);
21113
21114 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
21115 return Extract;
21116
21117 if (SDValue V = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
21118 return V;
21119
21120 if (DstVT.isVector())
21121 return lowerUINT_TO_FP_vec(Op, dl, DAG, Subtarget);
21122
21123 // Bail out when we don't have native conversion instructions.
21124 if (DstVT == MVT::f128)
21125 return SDValue();
21126
21127 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
21128 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
21129 // Conversions from unsigned i32 to f32/f64 are legal,
21130 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
21131 return Op;
21132 }
21133
21134 // Promote i32 to i64 and use a signed conversion on 64-bit targets.
21135 if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
21136 Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
21137 if (IsStrict)
21138 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
21139 {Chain, Src});
21140 return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
21141 }
21142
21143 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
21144 return V;
21145 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
21146 return V;
21147
21148 // The transform for i64->f64 isn't correct for 0 when rounding to negative
21149 // infinity. It produces -0.0, so disable under strictfp.
21150 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
21151 !IsStrict)
21152 return LowerUINT_TO_FP_i64(Op, dl, DAG, Subtarget);
21153 // The transform for i32->f64/f32 isn't correct for 0 when rounding to
21154 // negative infinity. So disable under strictfp. Using FILD instead.
21155 if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
21156 !IsStrict)
21157 return LowerUINT_TO_FP_i32(Op, dl, DAG, Subtarget);
21158 if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
21159 (DstVT == MVT::f32 || DstVT == MVT::f64))
21160 return SDValue();
21161
21162 // Make a 64-bit buffer, and use it to build an FILD.
21163 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
21164 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
21165 Align SlotAlign(8);
21166 MachinePointerInfo MPI =
21168 if (SrcVT == MVT::i32) {
21169 SDValue OffsetSlot =
21170 DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
21171 SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
21172 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
21173 OffsetSlot, MPI.getWithOffset(4), SlotAlign);
21174 std::pair<SDValue, SDValue> Tmp =
21175 BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
21176 if (IsStrict)
21177 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21178
21179 return Tmp.first;
21180 }
21181
21182 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
21183 SDValue ValueToStore = Src;
21184 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
21185 // Bitcasting to f64 here allows us to do a single 64-bit store from
21186 // an SSE register, avoiding the store forwarding penalty that would come
21187 // with two 32-bit stores.
21188 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21189 }
21190 SDValue Store =
21191 DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
21192 // For i64 source, we need to add the appropriate power of 2 if the input
21193 // was negative. We must be careful to do the computation in x87 extended
21194 // precision, not in SSE.
21195 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21196 SDValue Ops[] = {Store, StackSlot};
21197 SDValue Fild =
21198 DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
21199 SlotAlign, MachineMemOperand::MOLoad);
21200 Chain = Fild.getValue(1);
21201
21202 // Check whether the sign bit is set.
21203 SDValue SignSet = DAG.getSetCC(
21204 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
21205 Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
21206
21207 // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
21208 APInt FF(64, 0x5F80000000000000ULL);
21209 SDValue FudgePtr =
21210 DAG.getConstantPool(ConstantInt::get(*DAG.getContext(), FF), PtrVT);
21211 Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
21212
21213 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
21214 SDValue Zero = DAG.getIntPtrConstant(0, dl);
21215 SDValue Four = DAG.getIntPtrConstant(4, dl);
21216 SDValue Offset = DAG.